首页 > 解决方案 > 停止音频循环(audioplayers 包)

问题描述

我是 Flutter 编程的新手,我想创建一个应用程序,我需要一个音频文件在后台播放/循环。但是,当双击屏幕时,它应该停止。

音频保存在资产文件夹中。我可以播放它,但我不知道如何暂停/停止它。我正在使用这个

  @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');
        },

标签: flutterdart

解决方案


您必须获取的实例AudioPlayer才能停止文件,只需使用 await onplay()来获取实例并使用它,您可以调用stop(). 这是工作代码。

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
}

推荐阅读