play method
Future<bool>
play(
- String id,
- Source source, {
- required StopAction stopAction,
- double? volume,
- double? balance,
- AudioContext? ctx,
- Duration? position,
- 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);
//使用默认的context
var audioContext = ctx ?? audioContextDefault;
_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);
}