play method

Future<bool> play(
  1. String id,
  2. Source source, {
  3. required StopAction stopAction,
  4. double? volume,
  5. double? balance,
  6. AudioContext? ctx,
  7. Duration? position,
  8. PlayerMode? mode,
})

Implementation

Future<bool> play(
  String id,
  Source source, {
  required StopAction stopAction,
  double? volume,
  double? balance,
  AudioContext? ctx,
  Duration? position,
  PlayerMode? mode,
}) async {
  _setupSpeaker();
  //回掉之前的停止操作
  _stopAction?.call();

  //构建新的播放器
  if (players[id] == null) {
    players[id] = AudioPlayer(playerId: id);
  }
  //移除之前的播放器

  players.forEach((key, value) async {
    if (key != id) {
      await value.dispose();
    }
  });
  _subscription?.cancel();
  players.removeWhere((key, value) => key != id);
  // 桌面端不支持 AudioContext,传 null 避免触发 setAudioContext
  var audioContext = _isMobile ? (ctx ?? audioContextDefault) : null;

  _stopAction = stopAction;
  var audioPlayer = players[id];
  _subscription = audioPlayer!.onPlayerStateChanged.listen((event) {
    if (event == PlayerState.stopped || event == PlayerState.completed) {
      _stopAction?.call();
      _stopAction = null;
    }
  });
  return audioPlayer
      .play(
        source,
        volume: volume,
        balance: balance,
        ctx: audioContext,
        position: position,
        mode: mode,
      )
      .then((value) => true);
}