Flutter音频无法播放报错:仅Android M/23+或LOW_LATENCY模式支持调速
错误日志:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
lib\main.dart:1
E/flutter ( 6606): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(Unexpected error!, Changing the playback rate is only available for Android M/23+ or using LOW_LATENCY mode., java.lang.IllegalStateException: Changing the playback rate is only available for Android M/23+ or using LOW_LATENCY mode.
E/flutter ( 6606): at xyz.luan.audioplayers.player.MediaPlayerPlayer.setRate(MediaPlayerPlayer.kt:45)
E/flutter ( 6606): at xyz.luan.audioplayers.player.WrappedPlayer.configAndPrepare(WrappedPlayer.kt:307)
E/flutter ( 6606): at xyz.luan.audioplayers.player.WrappedPlayer.setSource(WrappedPlayer.kt:31)
E/flutter ( 6606): at xyz.luan.audioplayers.AudioplayersPlugin.handler(AudioplayersPlugin.kt:91)
E/flutter ( 6606): at xyz.luan.audioplayers.AudioplayersPlugin.access$handler(AudioplayersPlugin.kt:25)
E/flutter ( 6606): at xyz.luan.audioplayers.AudioplayersPlugin$onAttachedToEngine$1$1.invoke(AudioplayersPlugin.kt:41)
E/flutter ( 6606): at xyz.luan.audioplayers.AudioplayersPlugin$safeCall$1.invokeSuspend(AudioplayersPlugin.kt:62)
E/flutter ( 6606): at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
E/flutter ( 6606): at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
E/flutter ( 6606): at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
E/flutter ( 6606): at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
E/flutter ( 6606): at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
E/flutter ( 6606): at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
问题原因
你使用的audioplayers库在尝试修改播放速率时,当前测试设备的Android版本低于API 23(Android 6.0),且未开启LOW_LATENCY模式,导致系统不支持该操作。
解决办法
- 升级测试设备/模拟器版本:直接换成Android 6.0(M)或更高版本的模拟器镜像,重新运行项目即可。
- 开启LOW_LATENCY模式:如果不想升级系统,在初始化AudioPlayer时配置低延迟模式,示例代码:
final player = AudioPlayer(); // 配置音频上下文为低延迟模式 await player.setAudioContext(const AudioContext( android: AndroidAudioContext( audioMode: AndroidAudioMode.lowLatency, ), )); // 后续再设置播放源、速率等操作 await player.setSource(AssetSource('your_audio_file.mp3')); await player.setPlaybackRate(rate: 1.0); // 如果需要变速 await player.play(); - 移除播放速率设置:如果不需要变速功能,直接删掉代码中所有
setPlaybackRate相关的调用,避免触发报错逻辑。
内容的提问来源于stack exchange,提问作者clovis stanford

