Silent Tree
Silent Tree

Reputation: 1267

Stop audio loop (audioplayers package)

I'm new to flutter programming and I want to create an application, where I need an audio file to play/loop in the background. However it should stop, when double tapping on the screen.

The audio is saved in the assets folder. I am able to play it, but i don't know how to pause/stop it. I am using this package.

  @override
  Widget build(BuildContext context) {
    audioCache.play('rainsound.mp3', );
    return new Scaffold(
      child: new GestureDetector(
        onDoubleTap: () {
          //here I would like to stop the audio
          debugPrint('audio stopped');
        },

Upvotes: 13

Views: 9796

Answers (1)

CopsOnRoad
CopsOnRoad

Reputation: 268484

Update (audioplayers v1.0.1)

To Play:

final player = AudioPlayer();
// Assuming you have the file in "assets/audio/my_audio.mp3"
player.play(AssetSource('audio/my_audio.mp3'));

To Stop:

audioPlayer.stop();

You will have to get the instance of AudioPlayer to stop the file, simply use await on play() to get the instance and using this, you can call stop(). This is the working code.

AudioCache cache; // you have this
AudioPlayer player; // create this

void _playFile() async{
  player = await cache.play('my_audio.mp3'); // assign player here
}

void _stopFile() {
  player?.stop(); // stop the file like this
}

Upvotes: 29

Related Questions