You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Just Audio包是否自带续播功能?如何实现进度保存与停止清除

解决方案

要实现暂停保存播放进度、返回应用续播,以及停止清除进度的功能,你可以借助shared_preferences做本地持久化存储,配合just_audio的API完成逻辑,具体实现如下:

1. 添加依赖

在pubspec.yaml中加入shared_preferences依赖:

dependencies:
  flutter:
    sdk: flutter
  just_audio: ^x.x.x # 保留你当前使用的版本
  shared_preferences: ^2.2.2

执行flutter pub get完成依赖安装。

2. 初始化存储实例

在页面的State类中添加存储变量并初始化:

late SharedPreferences _prefs;
final String _progressKey = 'audio_play_progress'; // 用于存储进度的标识key

@override
void initState() {
  super.initState();
  _initPrefs();
}

void _initPrefs() async {
  _prefs = await SharedPreferences.getInstance();
}

3. 修改播放/暂停逻辑

更新原IconButton的点击事件,处理进度的保存与读取:

child: IconButton(
  onPressed: () async {
    if (_isplaying) {
      // 暂停时保存当前播放进度
      final currentPosition = await widget.audioPlayer.position;
      await _prefs.setDouble(_progressKey, currentPosition.inMilliseconds.toDouble());
      await widget.audioPlayer.pause();
    } else {
      // 播放前读取已保存的进度并跳转
      final savedProgress = _prefs.getDouble(_progressKey);
      if (savedProgress != null) {
        await widget.audioPlayer.seek(Duration(milliseconds: savedProgress.toInt()));
      }
      await widget.audioPlayer.play();
    }
    setState(() {
      _isplaying = !_isplaying;
    });
  },
  icon: Icon(
    _isplaying ? Icons.pause : Icons.play_arrow_rounded,
    size: 40,
  ),
),

4. 实现停止功能

添加停止按钮,完成暂停播放、重置位置、清除存储进度的逻辑:

child: IconButton(
  onPressed: () async {
    await widget.audioPlayer.pause();
    await widget.audioPlayer.seek(Duration.zero); // 将播放位置重置到开头
    await _prefs.remove(_progressKey); // 清除本地保存的进度
    setState(() {
      _isplaying = false;
    });
  },
  icon: const Icon(Icons.stop, size: 40),
),

关键说明

  • 用毫秒值存储进度,避免Duration类型的序列化问题
  • 所有异步操作(暂停、播放、跳转、存储读写)都需加await,保证逻辑执行顺序正确
  • 停止操作需同时重置播放位置和清除存储进度,避免下次播放时跳转到旧位置

内容的提问来源于stack exchange,提问作者Jadiel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:19:57