通知中心封面图显示

部分界面的信息更新
缓存系统初步引入
即将进入播放列表更新
This commit is contained in:
2026-08-25 23:09:17 +08:00
parent 0e8921742c
commit f2b4d1f46d
16 changed files with 454 additions and 161 deletions
+115 -85
View File
@@ -1,11 +1,15 @@
// lib/services/audio_player_handler.dart
import 'dart:io'; // ⭐ 添加
import 'dart:typed_data'; // ⭐ 添加
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:audio_service/audio_service.dart' as audio_service;
import '../audio/player_controller.dart';
import '../audio/playback_state_manager.dart';
import '../services/audio_service.dart';
import '../utils/file_provider_utils.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';
class AudioPlayerHandler extends audio_service.BaseAudioHandler {
final PlayerController _player = PlayerController();
@@ -15,18 +19,19 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
String? _currentTitle;
String? _currentArtist;
// ⭐ 唯一的位置变量
Duration _currentPosition = Duration.zero;
DateTime _lastPublishTime = DateTime.now();
static const Duration _publishInterval = Duration(milliseconds: 500);
// ⭐ 缓存 artwork 文件路径,避免重复写入
String? _currentArtworkPath;
AudioPlayerHandler() {
_player.playingStream.listen((playing) {
_state.updatePlaying(playing);
_publishState();
});
// ⭐ 位置更新:直接赋值给 _currentPosition
_player.positionStream.listen((position) {
_currentPosition = position;
_state.updatePosition(position);
@@ -34,7 +39,7 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
final now = DateTime.now();
if (now.difference(_lastPublishTime) >= _publishInterval) {
_lastPublishTime = now;
_updateMediaItemPosition(position);
// ⭐ 只保留 _publishStateOnly()
_publishStateOnly();
}
});
@@ -54,6 +59,7 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
});
}
// ---- 发布状态 ----
void _publishState() {
final state = _state.playbackState;
playbackState.add(audio_service.PlaybackState(
@@ -71,31 +77,112 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
void _publishStateOnly() {
final current = playbackState.value;
debugPrint(
'📡 [publishStateOnly] position=$_currentPosition, playing=${current.playing}',
);
'📡 [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(),
),
);
playbackState.add(audio_service.PlaybackState(
controls: current.controls.isNotEmpty
? current.controls
: _state.playbackState.controls,
processingState: _state.playbackState.processingState,
playing: current.playing,
androidCompactActionIndices: current.androidCompactActionIndices,
updatePosition: _currentPosition,
updateTime: DateTime.now(),
systemActions: const {
audio_service.MediaAction.seek,
},
));
}
// ---- 更新媒体信息 ----
void _updateMediaItem({
required String id,
required String title,
required String artist,
Duration? duration,
Uint8List? artwork,
}) {
debugPrint(
'📢 [handler] _updateMediaItem: artwork is ${artwork != null ? 'not null (${artwork.length} bytes)' : 'null'}');
_currentId = id;
_currentTitle = title;
_currentArtist = artist;
final position = _player.position;
debugPrint('📢 [handler] updateMediaItem: $title - $artist');
// ⭐ 异步处理 artwork(不阻塞主流程)
_handleArtwork(id, artwork).then((artUri) {
// 如果 artUri 变化,重新推送 MediaItem
final current = mediaItem.value;
if (current != null && current.artUri != artUri) {
debugPrint('📢 [handler] updating artUri: $artUri');
mediaItem.add(audio_service.MediaItem(
id: current.id,
title: current.title,
artist: current.artist,
duration: current.duration,
artUri: artUri,
extras: current.extras,
));
}
});
// 先推送不带封面图的 MediaItem(让 UI 尽快显示)
mediaItem.add(audio_service.MediaItem(
id: id,
title: title,
artist: artist,
duration: duration ?? _player.duration,
extras: {'position': position.inMilliseconds},
));
}
/// 处理封面图:保存到本地并生成 content URI
Future<Uri?> _handleArtwork(String id, Uint8List? artwork) async {
if (artwork == null || artwork.isEmpty) {
_currentArtworkPath = null;
return null;
}
try {
final dir = await getApplicationDocumentsDirectory();
final artworkDir = Directory('${dir.path}/artworks');
if (!await artworkDir.exists()) {
await artworkDir.create(recursive: true);
}
// 使用 md5 生成安全的文件名
final bytes = utf8.encode(id);
final digest = md5.convert(bytes);
final fileName = '$digest.jpg';
final path = '${artworkDir.path}/$fileName';
final file = File(path);
// 检查文件是否已存在
if (await file.exists()) {
final existingBytes = await file.readAsBytes();
if (existingBytes.length == artwork.length &&
existingBytes.hashCode == artwork.hashCode) {
_currentArtworkPath = path;
return await FileProviderUtils.getContentUri(file);
}
}
// 写入新文件
await file.writeAsBytes(artwork);
_currentArtworkPath = path;
debugPrint('📢 [handler] artwork saved: $path');
return await FileProviderUtils.getContentUri(file);
} catch (e) {
debugPrint('⚠️ [handler] artwork handling failed: $e');
return null;
}
}
// ---- 外部接口 ----
void updateNotification({
required String id,
required String title,
@@ -108,66 +195,10 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
artist: artist,
artwork: artwork,
);
_publishState();
}
void _updateMediaItem({
required String id,
required String title,
required String artist,
Duration? duration,
Uint8List? artwork,
}) {
_currentId = id;
_currentTitle = title;
_currentArtist = artist;
final position = _player.position;
debugPrint('📢 [handler] updateMediaItem: $title - $artist');
// ⭐ 如果有 artwork,保存为临时文件并设置 artUri
Uri? artUri;
if (artwork != null && artwork.isNotEmpty) {
try {
final tempDir = Directory.systemTemp;
final artPath = '${tempDir.path}/art_${id.hashCode}.jpg';
final artFile = File(artPath);
artFile.writeAsBytesSync(artwork);
artUri = Uri.file(artPath);
debugPrint('📢 [handler] artwork saved: $artPath');
} catch (e) {
debugPrint('⚠️ [handler] save artwork failed: $e');
}
}
mediaItem.add(audio_service.MediaItem(
id: id,
title: title,
artist: artist,
duration: duration ?? _player.duration,
artUri: artUri,
extras: {
'position': position.inMilliseconds,
},
));
}
void _updateMediaItemPosition(Duration position) {
final currentMediaItem = mediaItem.value;
if (currentMediaItem != null) {
mediaItem.add(audio_service.MediaItem(
id: currentMediaItem.id,
title: currentMediaItem.title,
artist: currentMediaItem.artist,
duration: currentMediaItem.duration,
artUri: currentMediaItem.artUri,
extras: {
'position': position.inMilliseconds,
...?currentMediaItem.extras,
},
));
}
}
// ---- 控制命令 ----
@override
Future<void> play() async {
debugPrint('▶️ [handler] play() called');
@@ -194,7 +225,6 @@ class AudioPlayerHandler extends audio_service.BaseAudioHandler {
debugPrint('⏩ [handler] seek() called: $position');
await _player.seek(position);
_currentPosition = position;
_updateMediaItemPosition(position);
_publishStateOnly();
}
+78 -25
View File
@@ -1,10 +1,13 @@
// lib/services/audio_service.dart
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:path_provider/path_provider.dart';
import 'playback_service.dart';
import '../metadata/metadata_service.dart';
import 'dart:typed_data';
import '../database/song_database.dart';
import '../utils/artwork_helper.dart';
enum PlayMode {
sequential,
@@ -44,7 +47,7 @@ class AudioService extends ChangeNotifier {
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);
@@ -55,7 +58,6 @@ class AudioService extends ChangeNotifier {
bool _handlingCompletion = false;
void Function(Song)? _onSongChanged;
// ⭐ 防 seek 覆盖标志
bool _isUserSeeking = false;
// ---- Getter ----
@@ -81,12 +83,10 @@ class AudioService extends ChangeNotifier {
}
}
// ---- 注册回调 ----
void setOnSongChanged(void Function(Song) callback) {
_onSongChanged = callback;
}
// ---- 切换播放模式 ----
void togglePlayMode() {
switch (_playMode) {
case PlayMode.sequential:
@@ -102,7 +102,6 @@ class AudioService extends ChangeNotifier {
notifyListeners();
}
// ---- 设置播放队列 ----
void setQueue(List<Song> queue, {int startIndex = 0}) {
if (queue.isEmpty) {
_clearQueue();
@@ -131,7 +130,6 @@ class AudioService extends ChangeNotifier {
stopPlay();
}
// ---- 播放指定歌曲 ----
Future<void> playSong(Song song) async {
if (_queue.isEmpty || _queue[_currentIndex].id != song.id) {
setQueue([song], startIndex: 0);
@@ -140,7 +138,6 @@ class AudioService extends ChangeNotifier {
}
}
// ---- 核心:播放当前歌曲 ----
void _playCurrent() {
if (_currentIndex < 0 || _currentIndex >= _queue.length) {
stopPlay();
@@ -159,13 +156,16 @@ class AudioService extends ChangeNotifier {
PlaybackService().play(song.url!);
// 延迟同步兜底(解决首次加载时 stream 未推送的问题)
_syncPlayerStateDelayed();
_loadMetadataForCurrentSong();
}
// ---- 加载 metadata ----
String _generateSongKey(String url, int fileSize, int modifiedTime) {
final raw = '$url|$fileSize|$modifiedTime';
return raw.hashCode.toString();
}
Future<void> _loadMetadataForCurrentSong() async {
if (_currentIndex < 0 || _currentIndex >= _queue.length) return;
final song = _queue[_currentIndex];
@@ -184,12 +184,13 @@ class AudioService extends ChangeNotifier {
title: metadata.title.isNotEmpty ? metadata.title : song.title,
artist: metadata.artist.isNotEmpty ? metadata.artist : song.artist,
url: song.url,
artwork: metadata.artwork,
// ⭐ 如果需要传递 artwork,可以在这里添加字段
artwork: metadata.artwork, // ✅ 已有
);
_queue[_currentIndex] = updatedSong;
_currentSong = updatedSong;
notifyListeners();
// ⭐ 传递完整的 updatedSong(包含 artwork
_onSongChanged?.call(updatedSong);
}
} catch (e) {
@@ -197,7 +198,70 @@ class AudioService extends ChangeNotifier {
}
}
// ---- 下一首 ----
/// 清除当前歌曲的缓存(metadata + 封面图 + 文件缓存),并强制重新播放
Future<void> clearCurrentSongCache() async {
if (_currentSong == null) return;
final song = _currentSong!;
final url = song.url ?? '';
if (url.isEmpty) return;
debugPrint('🗑️ [AudioService] clearing cache for: ${song.title}');
// 1. 获取当前索引
final currentIndex = _currentIndex;
// 2. 尝试获取文件信息生成 song_key
String songKey;
try {
final provider = MetadataService().getProviderForUrl(url);
final file = await provider.getFile(url);
if (file != null && await file.exists()) {
final stat = await file.stat();
songKey = _generateSongKey(
url, stat.size, stat.modified.millisecondsSinceEpoch);
} else {
songKey = url.hashCode.toString();
}
} catch (e) {
songKey = url.hashCode.toString();
}
// 3. 清除 SQLite 记录
final db = SongDatabase();
await db.deleteSong(songKey);
await db.deleteCache(songKey);
debugPrint('🗑️ [AudioService] SQLite records deleted: $songKey');
// 4. 删除封面图
await ArtworkHelper.deleteArtwork(songKey);
debugPrint('🗑️ [AudioService] artwork deleted');
// 5. 删除 metadata 临时缓存文件
try {
final cacheDir = await getTemporaryDirectory();
final cachePath = '${cacheDir.path}/metadata_${url.hashCode}.tmp';
final cacheFile = File(cachePath);
if (await cacheFile.exists()) {
await cacheFile.delete();
debugPrint('🗑️ [AudioService] temp cache file deleted');
}
} catch (e) {
// 忽略
}
// 6. 清除内存缓存
await MetadataService().clearCache(song.id);
debugPrint('🗑️ [AudioService] memory cache cleared');
// 7. 停止并重新播放
if (currentIndex >= 0 && currentIndex < _queue.length) {
stopPlay();
// 确保重新播放同一首歌
_playCurrent();
debugPrint('🔄 [AudioService] song reloaded');
}
}
void next() {
if (_queue.isEmpty) return;
@@ -215,7 +279,6 @@ class AudioService extends ChangeNotifier {
_playCurrent();
}
// ---- 上一首 ----
void previous() {
if (_queue.isEmpty) return;
@@ -241,7 +304,6 @@ class AudioService extends ChangeNotifier {
_playCurrent();
}
// ---- 播放/暂停 ----
void togglePlay() {
if (_currentSong == null) return;
@@ -252,7 +314,6 @@ class AudioService extends ChangeNotifier {
}
}
// ---- 停止播放 ----
void stopPlay() {
_currentSong = null;
_isPlaying = false;
@@ -263,19 +324,16 @@ class AudioService extends ChangeNotifier {
notifyListeners();
}
// ---- 跳转 ----
void seekTo(Duration position) {
_isUserSeeking = true;
PlaybackService().seek(position);
positionNotifier.value = position;
// 800ms 后重置标志(覆盖 media_kit 的 positionStream 推送窗口)
Future.delayed(const Duration(milliseconds: 800), () {
_isUserSeeking = false;
});
}
// ---- 清空队列 ----
void clearQueue() {
_queue.clear();
_currentIndex = -1;
@@ -285,7 +343,6 @@ class AudioService extends ChangeNotifier {
notifyListeners();
}
// ---- 主动状态同步(供 PlayerPage 调用) ----
void syncPlayerStateNow() {
final player = PlaybackService().player;
final pos = player.state.position;
@@ -306,7 +363,6 @@ class AudioService extends ChangeNotifier {
}
}
// ---- 延迟同步(兜底) ----
void _syncPlayerStateDelayed() {
syncPlayerStateNow();
Future.delayed(const Duration(milliseconds: 200), () {
@@ -317,7 +373,6 @@ class AudioService extends ChangeNotifier {
});
}
// ---- 监听 media_kit 状态 ----
void _startListening() {
if (_listening) return;
_listening = true;
@@ -335,7 +390,6 @@ class AudioService extends ChangeNotifier {
_subscriptions.add(
player.stream.position.listen((position) {
// ⭐ 如果是用户主动 seek,忽略这次推送(避免覆盖)
if (_isUserSeeking) {
debugPrint('🎯 [AudioService] positionStream ignored: user seeking');
return;
@@ -374,7 +428,6 @@ class AudioService extends ChangeNotifier {
_subscriptions.clear();
}
// ---- 防重入的完成事件处理 ----
void _onPlaybackCompleted() {
if (_handlingCompletion) {
debugPrint('⚠️ [service] completed ignored: already handling');