停止音频循环(audioplayers 包)

Sil*_*ree 10 dart flutter

我是 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');
        },
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 19

您必须获取 的实例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
}
Run Code Online (Sandbox Code Playgroud)

  • `?.` 用于检查 null,因此仅当 `player != null` 时才会调用 `stop()`。 (2认同)