Flutter音频播放问题:调用audioPlayer.seek()无法从指定时间启动音频
解决Flutter AudioPlayer调用seek()后音频仍从头播放的问题
可能的原因及解决方案:
确保seek与play的调用顺序正确
错误的调用顺序(先play后seek)会导致音频先从头启动,再跳转位置,甚至可能失效。正确流程是:- 若音频处于停止状态:先设置音频源 → 调用
seek()定位到目标位置 → 调用play() - 若音频处于暂停状态:先调用
seek()→ 调用resume()恢复播放
示例代码:
Future<void> restoreAudioPlayback() async { // 从本地存储读取保存的播放进度 final prefs = await SharedPreferences.getInstance(); final savedSeconds = prefs.getInt('saved_audio_progress') ?? 0; final targetPos = Duration(seconds: savedSeconds); // 处理停止状态的音频 if (audioPlayer.state == PlayerState.stopped) { await audioPlayer.setSource(AssetSource('audio_file.mp3')); } // 先定位再播放/恢复 await audioPlayer.seek(targetPos); if (audioPlayer.state == PlayerState.paused) { await audioPlayer.resume(); } else { await audioPlayer.play(); } }- 若音频处于停止状态:先设置音频源 → 调用
确认播放进度的保存逻辑正确
需要在音频播放时实时监听位置变化,确保进度值被准确持久化:audioPlayer.onPositionChanged.listen((currentPos) { SharedPreferences.getInstance().then((prefs) { prefs.setInt('saved_audio_progress', currentPos.inSeconds); }); });验证seek参数的有效性
避免传入超出音频总时长的位置,可先校验后再seek:final totalDuration = await audioPlayer.getDuration(); if (totalDuration != null && targetPos > totalDuration) { targetPos = totalDuration; } await audioPlayer.seek(targetPos);检查音频库版本
若使用audioplayers库,旧版本可能存在seek相关bug,确保依赖最新稳定版:dependencies: audioplayers: ^4.0.1 # 替换为当前最新稳定版
内容的提问来源于stack exchange,提问作者Dhanrajsinh Parmar
相关产品推荐
相关产品推荐

