我不能 stop/pause audioplayers 中的歌曲

i cannot stop/pause a song in audioplayers

我在我的代码中使用 audioplayers 插件。

我可以播放音频但我不能stop/pause音频。以下是我用来 play/stop 音频的函数。

  Future<void> onPlay({@required filepath, @required index}) async {
    AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
    if (!_isPlaying) {
      int result = await audioPlayer.play(filepath, isLocal: true);
      if (result == 1) {
        setState(() {
          _isPlaying = true;
          _selectedIndex = index;
        });
      }
    } else {
      int result = await audioPlayer.stop();
      if (result == 1) {
        setState(() {
          _isPlaying = false;
        });
      }
    }
  }
}

您每次调用 onPlay 时都会实例化一个新的 AudioPlayer audioPlayer 对象,这使您以后无法停止同一个玩家。

将您的 AudioPlayer audioPlayer 存储在某处的状态。

AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);

Future<void> onPlay({@required filepath, @required index}) async {
  if (!_isPlaying) {
    int result = await audioPlayer.play(filepath, isLocal: true);
    if (result == 1) {
      setState(() {
        _isPlaying = true;
        _selectedIndex = index;
      });
    }
  } else {
    int result = await audioPlayer.stop();
    if (result == 1) {
      setState(() {
        _isPlaying = false;
      });
    }
  }
}