Compare commits

4 Commits
4 changed files with 135 additions and 27 deletions
+9
View File
@@ -52,6 +52,15 @@ void main() async {
// ⭐ 创建 HandlerAudioService 稍后初始化) // ⭐ 创建 HandlerAudioService 稍后初始化)
_audioHandler = AudioPlayerHandler(); _audioHandler = AudioPlayerHandler();
// ⭐ 注册切歌回调:当歌曲切换时,立即更新通知
AudioService().setOnSongChanged((song) {
_audioHandler!.updateNotification(
id: song.id,
title: song.title,
artist: song.artist,
);
});
runApp( runApp(
MultiProvider( MultiProvider(
providers: [ providers: [
+111 -23
View File
@@ -4,42 +4,131 @@ import 'package:flutter/foundation.dart';
import 'package:audio_service/audio_service.dart' as audio_service; import 'package:audio_service/audio_service.dart' as audio_service;
import '../audio/player_controller.dart'; import '../audio/player_controller.dart';
import '../audio/playback_state_manager.dart'; import '../audio/playback_state_manager.dart';
import '../services/audio_service.dart'; // 你自己的业务 AudioService import '../services/audio_service.dart';
class AudioPlayerHandler extends audio_service.BaseAudioHandler { class AudioPlayerHandler extends audio_service.BaseAudioHandler {
final PlayerController _player = PlayerController(); final PlayerController _player = PlayerController();
final PlaybackStateManager _state = PlaybackStateManager(); final PlaybackStateManager _state = PlaybackStateManager();
String? _currentId;
String? _currentTitle;
String? _currentArtist;
// ⭐ 唯一的位置变量
Duration _currentPosition = Duration.zero;
DateTime _lastPublishTime = DateTime.now();
static const Duration _publishInterval = Duration(milliseconds: 500);
AudioPlayerHandler() { AudioPlayerHandler() {
// ---- 监听播放状态变化,同步到通知栏 ----
_player.playingStream.listen((playing) { _player.playingStream.listen((playing) {
_state.updatePlaying(playing); _state.updatePlaying(playing);
_publishState(); _publishState();
}); });
// ⭐ 位置更新:直接赋值给 _currentPosition
_player.positionStream.listen((position) { _player.positionStream.listen((position) {
_currentPosition = position;
_state.updatePosition(position); _state.updatePosition(position);
final current = playbackState.value;
playbackState.add(audio_service.PlaybackState( final now = DateTime.now();
controls: current.controls, if (now.difference(_lastPublishTime) >= _publishInterval) {
processingState: current.processingState, _lastPublishTime = now;
playing: current.playing, _updateMediaItemPosition(position);
androidCompactActionIndices: current.androidCompactActionIndices, _publishStateOnly();
updateTime: DateTime.now(), }
));
}); });
_player.durationStream.listen((duration) { _player.durationStream.listen((duration) {
_state.updateDuration(duration); _state.updateDuration(duration);
if (_currentId != null && _currentTitle != null) {
_updateMediaItem(
id: _currentId!,
title: _currentTitle!,
artist: _currentArtist!,
duration: duration,
);
}
_publishState(); _publishState();
}); });
}
// ⭐ 已删除 completed 监听,交由 AudioService 统一处理 void _updateMediaItemPosition(Duration position) {
// _player.completedStream.listen((_) { ... }); final currentMediaItem = mediaItem.value;
if (currentMediaItem != null) {
mediaItem.add(audio_service.MediaItem(
id: currentMediaItem.id,
title: currentMediaItem.title,
artist: currentMediaItem.artist,
duration: currentMediaItem.duration,
extras: {
'position': position.inMilliseconds,
...?currentMediaItem.extras,
},
));
}
} }
void _publishState() { void _publishState() {
playbackState.add(_state.playbackState); final state = _state.playbackState;
playbackState.add(audio_service.PlaybackState(
controls: state.controls,
processingState: state.processingState,
playing: state.playing,
androidCompactActionIndices: state.androidCompactActionIndices,
updateTime: DateTime.now(),
));
}
void _publishStateOnly() {
final current = playbackState.value;
debugPrint(
'📡 [publishStateOnly] position=$_currentPosition, playing=${current.playing}',
);
playbackState.add(
audio_service.PlaybackState(
controls: current.controls.isNotEmpty
? current.controls
: _state.playbackState.controls,
processingState: _state.playbackState.processingState,
playing: current.playing,
androidCompactActionIndices: current.androidCompactActionIndices,
// ⭐ 声明支持 seek
systemActions: const {
audio_service.MediaAction.seek,
},
updatePosition: _currentPosition,
updateTime: DateTime.now(),
),
);
}
void _updateMediaItem({
required String id,
required String title,
required String artist,
Duration? duration,
}) {
_currentId = id;
_currentTitle = title;
_currentArtist = artist;
final position = _player.position;
debugPrint(
'📢 [handler] updateMediaItem: $title - $artist (position=${position.inSeconds}s)');
mediaItem.add(audio_service.MediaItem(
id: id,
title: title,
artist: artist,
duration: duration ?? _player.duration,
extras: {
'position': position.inMilliseconds,
},
));
} }
void updateNotification({ void updateNotification({
@@ -47,38 +136,38 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
required String title, required String title,
required String artist, required String artist,
}) { }) {
debugPrint('📢 [handler] updateNotification: $title'); _updateMediaItem(id: id, title: title, artist: artist);
mediaItem.add(audio_service.MediaItem( _publishState();
id: id,
title: title,
artist: artist,
duration: _player.duration,
));
} }
// ---- 系统控制命令 ----
@override @override
Future<void> play() async { Future<void> play() async {
debugPrint('▶️ [handler] play() called'); debugPrint('▶️ [handler] play() called');
_player.play(); _player.play();
_publishState();
} }
@override @override
Future<void> pause() async { Future<void> pause() async {
debugPrint('⏸️ [handler] pause() called'); debugPrint('⏸️ [handler] pause() called');
_player.pause(); _player.pause();
_publishState();
} }
@override @override
Future<void> stop() async { Future<void> stop() async {
debugPrint('⏹️ [handler] stop() called'); debugPrint('⏹️ [handler] stop() called');
_player.stop(); _player.stop();
_publishState();
} }
@override @override
Future<void> seek(Duration position) async { Future<void> seek(Duration position) async {
debugPrint('⏩ [handler] seek() called: $position'); debugPrint('⏩ [handler] seek() called: $position');
_player.seek(position); await _player.seek(position);
_currentPosition = position;
_updateMediaItemPosition(position);
_publishStateOnly();
} }
@override @override
@@ -113,7 +202,6 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
} }
break; break;
default: default:
// 其他按钮 fallback
if (_player.isPlaying) { if (_player.isPlaying) {
await pause(); await pause();
} else { } else {
+13 -2
View File
@@ -51,6 +51,9 @@ class AudioService extends ChangeNotifier {
// ⭐ 防重入标志 // ⭐ 防重入标志
bool _handlingCompletion = false; bool _handlingCompletion = false;
// ⭐ 歌曲切换回调(用于通知 Handler 更新 MediaItem
void Function(Song)? _onSongChanged;
// ---- Getter(高频字段不走 ChangeNotifier ---- // ---- Getter(高频字段不走 ChangeNotifier ----
Song? get currentSong => _currentSong; Song? get currentSong => _currentSong;
bool get isPlaying => _isPlaying; bool get isPlaying => _isPlaying;
@@ -75,6 +78,11 @@ class AudioService extends ChangeNotifier {
} }
} }
// ---- 注册歌曲切换回调 ----
void setOnSongChanged(void Function(Song) callback) {
_onSongChanged = callback;
}
// ---- 切换播放模式 ---- // ---- 切换播放模式 ----
void togglePlayMode() { void togglePlayMode() {
switch (_playMode) { switch (_playMode) {
@@ -138,6 +146,9 @@ class AudioService extends ChangeNotifier {
final song = _queue[_currentIndex]; final song = _queue[_currentIndex];
_currentSong = song; _currentSong = song;
// ⭐ 切歌时触发回调(通知 Handler 更新 MediaItem
_onSongChanged?.call(song);
// ⭐ 重置进度(用 ValueNotifier // ⭐ 重置进度(用 ValueNotifier
positionNotifier.value = Duration.zero; positionNotifier.value = Duration.zero;
durationNotifier.value = Duration.zero; durationNotifier.value = Duration.zero;
@@ -266,7 +277,7 @@ class AudioService extends ChangeNotifier {
}), }),
); );
// ⭐ 唯一监听 completed 的地方 // ⭐ 唯一监听 completed 的地方(带防重入)
_subscriptions.add( _subscriptions.add(
player.stream.completed.listen((_) { player.stream.completed.listen((_) {
_onPlaybackCompleted(); _onPlaybackCompleted();
@@ -282,7 +293,7 @@ class AudioService extends ChangeNotifier {
_subscriptions.clear(); _subscriptions.clear();
} }
// ⭐ 防重入 // ⭐ 防重入的完成事件处理
void _onPlaybackCompleted() { void _onPlaybackCompleted() {
if (_handlingCompletion) { if (_handlingCompletion) {
debugPrint('⚠️ [service] completed ignored: already handling'); debugPrint('⚠️ [service] completed ignored: already handling');
+2 -2
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 1.0.2+1 version: 1.0.3+1
environment: environment:
sdk: ^3.0.0 sdk: ^3.0.0
@@ -36,7 +36,7 @@ dependencies:
provider: ^6.1.2 provider: ^6.1.2
dio: ^5.4.0 # HTTP 客户端 dio: ^5.4.0 # HTTP 客户端
xml: ^6.5.0 xml: ^6.5.0
audio_service: ^0.18.13 audio_service: ^0.18.19
audio_session: ^0.1.21 audio_session: ^0.1.21
permission_handler: ^11.3.1 permission_handler: ^11.3.1
flutter_cache_manager: ^3.3.1 flutter_cache_manager: ^3.3.1