我无法停止/暂停音频播放器中的歌曲

时间:2021-06-07 14:30:13

标签: flutter dart audio-player

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

我可以播放音频,但无法停止/暂停音频。以下是我用来播放/停止音频的功能。

  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;
        });
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

每次调用 AudioPlayer audioPlayer 时都会实例化一个新的 onPlay 对象,这让您以后无法阻止同一个播放器。

将您的 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;
      });
    }
  }
}