权限配置暂时到此,后台播放问题并入生命周期管理同步开发

This commit is contained in:
2026-08-20 22:07:59 +08:00
parent b2c7582ca7
commit f94cda4234
9 changed files with 787 additions and 364 deletions
+90
View File
@@ -0,0 +1,90 @@
// lib/services/audio_player_handler.dart
import 'package:audio_service/audio_service.dart';
import 'playback_service.dart';
import 'audio_service.dart' as local_audio;
class AudioPlayerHandler extends BaseAudioHandler {
final PlaybackService _playback = PlaybackService();
late final local_audio.AudioService _localAudio;
MediaItem? _currentMediaItem;
AudioPlayerHandler() {
_localAudio = local_audio.AudioService();
// 1. 监听播放状态(只更新 playing)
_playback.player.stream.playing.listen((playing) {
playbackState.add(playbackState.value.copyWith(
playing: playing,
));
});
// 2. ⭐ 进度更新:跳过,因为当前版本不支持 position 参数
// 通知栏进度条不会动,但播放/暂停/切歌功能正常
// 如果后续需要,可以升级 audio_service 版本或改用其他方案
// 3. 监听播放完成(触发下一首)
_playback.player.stream.completed.listen((_) {
_localAudio.next();
});
// 4. 监听时长变化,更新 MediaItem
_playback.player.stream.duration.listen((duration) {
if (_currentMediaItem != null) {
_currentMediaItem = _currentMediaItem!.copyWith(duration: duration);
mediaItem.add(_currentMediaItem);
}
});
}
/// 外部调用更新通知栏
void updateNotification({
required String id,
required String title,
required String artist,
}) {
_currentMediaItem = MediaItem(
id: id,
title: title,
artist: artist,
duration: _playback.player.state.duration,
);
mediaItem.add(_currentMediaItem);
}
// ---- AudioHandler 接口实现 ----
@override
Future<void> play() async {
_playback.resume();
}
@override
Future<void> pause() async {
_playback.pause();
}
@override
Future<void> stop() async {
_playback.stop();
}
@override
Future<void> seek(Duration position) async {
_playback.seek(position);
}
@override
Future<void> skipToNext() async {
_localAudio.next();
}
@override
Future<void> skipToPrevious() async {
_localAudio.previous();
}
@override
Future<void> click([MediaButton button = MediaButton.media]) async {
// 默认行为:打开 App
}
}
+52 -86
View File
@@ -4,18 +4,12 @@ import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'playback_service.dart';
// ============================================================
// 播放模式
// ============================================================
enum PlayMode {
sequential, // 顺序循环
repeatOne, // 单曲循环
shuffle, // 随机播放
sequential,
repeatOne,
shuffle,
}
// ============================================================
// 歌曲模型
// ============================================================
class Song {
final String id;
final String title;
@@ -30,49 +24,43 @@ class Song {
});
}
// ============================================================
// AudioService - 播放状态管理与 UI 数据源
// ============================================================
class AudioService extends ChangeNotifier {
// ---------- 单例 ----------
static final AudioService _instance = AudioService._internal();
factory AudioService() => _instance;
AudioService._internal();
// ---------- 播放状态 ----------
// ---- 基础状态(低频,触发 UI 重建) ----
Song? _currentSong;
bool _isPlaying = false;
Duration _position = Duration.zero;
Duration _duration = Duration.zero;
Duration _bufferedPosition = Duration.zero;
// ---------- 播放模式 ----------
PlayMode _playMode = PlayMode.sequential;
// ---------- 播放队列 ----------
// ---- 播放队列 ----
List<Song> _queue = [];
int _currentIndex = -1;
// ---------- 随机播放相关 ----------
List<int> _shuffledIndices = [];
int _shuffledIndex = -1;
// ---------- 监听控制 ----------
// ---- ⭐ 高频进度(用 ValueNotifier,不触发全局重建) ----
final ValueNotifier<Duration> positionNotifier = ValueNotifier(Duration.zero);
final ValueNotifier<Duration> durationNotifier = ValueNotifier(Duration.zero);
final ValueNotifier<Duration> bufferedNotifier = ValueNotifier(Duration.zero);
bool _listening = false;
final List<StreamSubscription> _subscriptions = [];
// ---------- Getter ----------
// ---- Getter(高频字段不走 ChangeNotifier ----
Song? get currentSong => _currentSong;
bool get isPlaying => _isPlaying;
Duration get position => _position;
Duration get duration => _duration;
Duration get bufferedPosition => _bufferedPosition;
PlayMode get playMode => _playMode;
List<Song> get queue => List.unmodifiable(_queue);
int get currentIndex => _currentIndex;
bool get hasQueue => _queue.isNotEmpty;
// ---------- 播放模式图标 ----------
// ---- 兼容旧代码:提供 getter 返回 ValueNotifier 的值 ----
Duration get position => positionNotifier.value;
Duration get duration => durationNotifier.value;
Duration get bufferedPosition => bufferedNotifier.value;
IconData get playModeIcon {
switch (_playMode) {
case PlayMode.sequential:
@@ -84,7 +72,7 @@ class AudioService extends ChangeNotifier {
}
}
// ---------- 播放模式切换 ----------
// ---- 切换播放模式 ----
void togglePlayMode() {
switch (_playMode) {
case PlayMode.sequential:
@@ -100,7 +88,7 @@ class AudioService extends ChangeNotifier {
notifyListeners();
}
// ---------- 设置播放队列 ----------
// ---- 设置播放队列 ----
void setQueue(List<Song> queue, {int startIndex = 0}) {
if (queue.isEmpty) {
_clearQueue();
@@ -110,7 +98,6 @@ class AudioService extends ChangeNotifier {
_queue = List.from(queue);
_currentIndex = startIndex.clamp(0, _queue.length - 1);
// 初始化随机播放索引
_shuffledIndices = List.generate(_queue.length, (i) => i);
_shuffledIndices.shuffle();
_shuffledIndex = _shuffledIndices.indexOf(_currentIndex);
@@ -119,11 +106,9 @@ class AudioService extends ChangeNotifier {
_currentIndex = _shuffledIndices[0];
}
// 播放当前歌曲
_playCurrent();
}
// ---------- 清空队列 ----------
void _clearQueue() {
_queue.clear();
_currentIndex = -1;
@@ -132,18 +117,15 @@ class AudioService extends ChangeNotifier {
stopPlay();
}
// ---------- 播放指定歌曲(外部入口) ----------
// ---- 播放指定歌曲 ----
Future<void> playSong(Song song) async {
// 如果当前队列不包含这首歌,替换队列
if (_queue.isEmpty || _queue[_currentIndex].id != song.id) {
setQueue([song], startIndex: 0);
} else {
// 如果已经在队列中,直接播放
_playCurrent();
}
}
// ---------- 播放当前索引歌曲 ----------
void _playCurrent() {
if (_currentIndex < 0 || _currentIndex >= _queue.length) {
stopPlay();
@@ -152,9 +134,11 @@ class AudioService extends ChangeNotifier {
final song = _queue[_currentIndex];
_currentSong = song;
_position = Duration.zero;
_duration = Duration.zero;
_bufferedPosition = Duration.zero;
// ⭐ 重置进度(用 ValueNotifier
positionNotifier.value = Duration.zero;
durationNotifier.value = Duration.zero;
bufferedNotifier.value = Duration.zero;
_startListening();
notifyListeners();
@@ -163,15 +147,13 @@ class AudioService extends ChangeNotifier {
return;
}
// 由 PlaybackService 实际播放,状态由流更新
PlaybackService().play(song.url!);
}
// ---------- 播放下一首 ----------
// ---- 下一首 ----
void next() {
if (_queue.isEmpty) return;
// 随机模式
if (_playMode == PlayMode.shuffle) {
if (_shuffledIndices.isEmpty) return;
final nextIdx = (_shuffledIndex + 1) % _shuffledIndices.length;
@@ -181,17 +163,15 @@ class AudioService extends ChangeNotifier {
return;
}
// 顺序/单曲模式
final nextIdx = (_currentIndex + 1) % _queue.length;
_currentIndex = nextIdx;
_playCurrent();
}
// ---------- 播放上一首 ----------
// ---- 上一首 ----
void previous() {
if (_queue.isEmpty) return;
// 随机模式
if (_playMode == PlayMode.shuffle) {
if (_shuffledIndices.isEmpty) return;
final prevIdx = (_shuffledIndex - 1) % _shuffledIndices.length;
@@ -205,7 +185,6 @@ class AudioService extends ChangeNotifier {
return;
}
// 顺序/单曲模式
final prevIdx = (_currentIndex - 1) % _queue.length;
if (prevIdx < 0) {
_currentIndex = _queue.length - 1;
@@ -215,7 +194,7 @@ class AudioService extends ChangeNotifier {
_playCurrent();
}
// ---------- 播放/暂停切换 ----------
// ---- 播放/暂停 ----
void togglePlay() {
if (_currentSong == null) return;
@@ -224,39 +203,21 @@ class AudioService extends ChangeNotifier {
} else {
PlaybackService().resume();
}
// 状态由 player.stream.playing 更新
}
// ---------- 停止播放 ----------
void stopPlay() {
_currentSong = null;
_isPlaying = false;
_position = Duration.zero;
_duration = Duration.zero;
_bufferedPosition = Duration.zero;
positionNotifier.value = Duration.zero;
durationNotifier.value = Duration.zero;
bufferedNotifier.value = Duration.zero;
_stopListening();
notifyListeners();
}
// ---------- Seek ----------
void seekTo(Duration position) {
PlaybackService().seek(position);
_position = position;
notifyListeners();
}
// ---------- 处理播放结束 ----------
void _onPlaybackCompleted() {
if (_queue.isEmpty) return;
// 单曲循环模式
if (_playMode == PlayMode.repeatOne) {
_playCurrent();
return;
}
// 其他模式:播放下一首
next();
positionNotifier.value = position;
}
void clearQueue() {
@@ -268,7 +229,7 @@ class AudioService extends ChangeNotifier {
notifyListeners();
}
// ---------- 监听 media_kit 状态 ----------
// ---- 监听 media_kit 状态 ----
void _startListening() {
if (_listening) return;
_listening = true;
@@ -279,39 +240,30 @@ class AudioService extends ChangeNotifier {
player.stream.playing.listen((playing) {
if (_isPlaying != playing) {
_isPlaying = playing;
notifyListeners();
notifyListeners(); // 只有播放状态变化才刷新
}
}),
);
// ⭐ 进度更新:只更新 ValueNotifier,不触发全局重建
_subscriptions.add(
player.stream.position.listen((position) {
if (_position != position) {
_position = position;
notifyListeners();
}
positionNotifier.value = position;
}),
);
_subscriptions.add(
player.stream.duration.listen((duration) {
if (_duration != duration) {
_duration = duration;
notifyListeners();
}
durationNotifier.value = duration;
}),
);
_subscriptions.add(
player.stream.buffer.listen((buffer) {
if (_bufferedPosition != buffer) {
_bufferedPosition = buffer;
notifyListeners();
}
bufferedNotifier.value = buffer;
}),
);
// ✅ 播放结束监听
_subscriptions.add(
player.stream.completed.listen((_) {
_onPlaybackCompleted();
@@ -327,9 +279,23 @@ class AudioService extends ChangeNotifier {
_subscriptions.clear();
}
// ---------- 资源释放 ----------
void _onPlaybackCompleted() {
if (_queue.isEmpty) return;
if (_playMode == PlayMode.repeatOne) {
_playCurrent();
return;
}
next();
}
@override
void dispose() {
_stopListening();
positionNotifier.dispose();
durationNotifier.dispose();
bufferedNotifier.dispose();
PlaybackService().dispose();
super.dispose();
}