Flutter:如何停止播放声音

时间:2021-01-03 15:01:16

标签: flutter dart

我有播放声音的 Button1。 (代码如下)

AudioPlayer cache;
AudioPlayer player;
    
void _playFile(String yol) async {
     print(yol);
     AudioCache player = AudioCache();                                                         
     player.play('bird1.mp3'); // assign player here
}

另一个按钮(BUTTON2)必须停止声音。当我按下 BUTTON1 时,声音开始播放。但即使我去以前的页面声音仍然在播放。

Button2 执行这段代码:

void cancelPlay() {
   print("stop");
   player.pause();
}

错误是:

The method 'pause' was called on null.
Receiver: null
Tried calling: pause()

1 个答案:

答案 0 :(得分:0)

您需要在主范围内初始化您的播放器。如果您在 playFile 方法中初始化它,它将无法访问。

AudioPlayer cache; // You need to initialize it too!

AudioCache player = AudioCache(); // Here, we initialized the player.                                                         


void _playFile(String yol) async {
     print(yol);
     player.play('bird1.mp3'); // assign player here
}

void cancelPlay() {
   print("stop");
   player.pause();
}