Search code examples
flutteraudioflame

Flame Audio or Audio Player does not stop the sound


Working with Flame and Flame Audio, I cannot resolve an issue. The stop function on AudioPlayer returned by FlameAudio, does not stop playing the loop. I am not sure whether this is a problem in my code, a problem in AudioPlayer, or a problem of FlameAudio.

Below is the piece of code that starts the sound on start, and should stop it on end or cancel. With single pointer dragging it works. However, when using multidrag with multiplee pointers, and releasing all at once the sound keeps playing. The code should play only one sound while at least one drag is active.

Can anyone tell me, if I am doing something wrong or is there a bug. The minimum working example, which exhibits the problem on my phone, is available at https://github.com/markohrastovec/flame_audio_test.

  @override
  void onDragStart(int pointerId, DragStartInfo info) async {
    if (loopPlayer == null && activeDrag.isEmpty) {
      loopPlayer = await FlameAudio.audioCache.loop('sfx/flame.mp3');
    }
    activeDrag.add(pointerId);
  }

  @override
  void onDragEnd(int pointerId, DragEndInfo info) async {
    activeDrag.remove(pointerId);
    if (loopPlayer != null && activeDrag.isEmpty) {
      int result = await loopPlayer!.stop();
      loopPlayer = null;
    }
  }

  @override
  void onDragCancel(int pointerId) async {
    activeDrag.remove(pointerId);
    if (loopPlayer != null && activeDrag.isEmpty) {
      int result = await loopPlayer!.stop();
      loopPlayer = null;
    }
  }


Solution

  • I think this is due to the onDragStart method being async and it actually creates multiple players and replaces the first created one with a new one in the variable. Does this happen if you do something like this in onDragStart instead:

      @override
      void onDragStart(int pointerId, DragStartInfo info) async {
        if (loopPlayer == null && activeDrag.isEmpty) {
          activeDrag.add(pointerId);
          loopPlayer = await FlameAudio.audioCache.loop('sfx/flame.mp3');
        } else {
          activeDrag.add(pointerId);
        }
      }