我使用just_audio: ^0.9.29
来播放音频。页面中包含TabBar()
和Two Tabs
。播放器在第一个选项卡内
AudioPlayer代码:
GestureDetector(
onTap: () => taskerProfileViewModel.playAudio(),
child: CircleAvatar(
backgroundColor: kBlack,
child: taskerProfileViewModel.isPlaying.value
? const Icon(
Icons.pause,
color: kWhite,
)
: const Icon(
Icons.play_arrow,
color: kWhite,
),
),
);
void setAudioUrl({required String url}) async {
audioPlayer.setUrl("$baseUrl/$url", initialPosition: Duration.zero);
Duration? audioDuration;
try {
audioDuration = await audioPlayer.load();
} on PlayerInterruptedException catch (e) {
if (kDebugMode) {
print("Exception $e");
}
}
if (audioDuration != null) {
audioEndTime.value =
"${audioDuration.inMinutes.remainder(60).toString().padLeft(2, "0")}:${audioDuration.inSeconds.remainder(60).toString().padLeft(2, "0")}";
}
}
我正在调用initstate
中的setAudioUrl()
函数。
当我交换标签没有问题。但是,当我点击标签,音频播放器抛出这个异常PlayerInterruptedException (Connection aborted)
.
如何捕获并忽略此异常?
setUrl
应该在try catch
块内,这是一个异步方法,所以它需要一个await
关键字,试试这段代码:
void setAudioUrl({required String url}) async {
Duration? audioDuration;
try {
await audioPlayer.setUrl("$baseUrl/$url", initialPosition: Duration.zero);
audioDuration = await audioPlayer.load();
} on PlayerInterruptedException catch (e) {
if (kDebugMode) {
print("Exception $e");
}
}
if (audioDuration != null) {
audioEndTime.value =
"${audioDuration.inMinutes.remainder(60).toString().padLeft(2, "0")}:${audioDuration.inSeconds.remainder(60).toString().padLeft(2, "0")}";
}
}
希望有帮助。