568 lines
16 KiB
Dart
568 lines
16 KiB
Dart
// 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' as media_kit; // ⭐ 加别名
|
||
import 'package:path_provider/path_provider.dart';
|
||
import 'playback_service.dart';
|
||
import '../metadata/metadata_service.dart';
|
||
import '../database/song_database.dart';
|
||
import '../utils/artwork_helper.dart';
|
||
import '../repositories/playlist_repository.dart';
|
||
import '../models/playlist.dart'; // ⭐ 你的 Playlist 模型
|
||
|
||
enum PlayMode {
|
||
sequential,
|
||
repeatOne,
|
||
shuffle,
|
||
}
|
||
|
||
class Song {
|
||
final String id;
|
||
final String title;
|
||
final String artist;
|
||
final String? url;
|
||
final Uint8List? artwork;
|
||
|
||
Song({
|
||
required this.id,
|
||
required this.title,
|
||
required this.artist,
|
||
this.url,
|
||
this.artwork,
|
||
});
|
||
}
|
||
|
||
class AudioService extends ChangeNotifier {
|
||
static final AudioService _instance = AudioService._internal();
|
||
factory AudioService() => _instance;
|
||
AudioService._internal();
|
||
|
||
// ---- 基础状态 ----
|
||
Song? _currentSong;
|
||
bool _isPlaying = false;
|
||
PlayMode _playMode = PlayMode.sequential;
|
||
|
||
// ---- 播放队列 ----
|
||
List<Song> _queue = [];
|
||
int _currentIndex = -1;
|
||
List<int> _shuffledIndices = [];
|
||
int _shuffledIndex = -1;
|
||
|
||
// ---- 当前播放的歌单 ID(用于模式同步) ----
|
||
String? _currentPlaylistId;
|
||
|
||
// ---- 高频进度 ----
|
||
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 = [];
|
||
|
||
bool _handlingCompletion = false;
|
||
void Function(Song)? _onSongChanged;
|
||
|
||
bool _isUserSeeking = false;
|
||
|
||
// ⭐ 播放代数:每次切歌递增,用于校验异步任务是否过期
|
||
int _playbackGeneration = 0;
|
||
|
||
// ---- Repository ----
|
||
final SongDatabase _db = SongDatabase();
|
||
final PlaylistRepository _playlistRepo = PlaylistRepository();
|
||
|
||
// ---- Getter ----
|
||
Song? get currentSong => _currentSong;
|
||
bool get isPlaying => _isPlaying;
|
||
PlayMode get playMode => _playMode;
|
||
List<Song> get queue => List.unmodifiable(_queue);
|
||
int get currentIndex => _currentIndex;
|
||
bool get hasQueue => _queue.isNotEmpty;
|
||
String? get currentPlaylistId => _currentPlaylistId;
|
||
|
||
Duration get position => positionNotifier.value;
|
||
Duration get duration => durationNotifier.value;
|
||
Duration get bufferedPosition => bufferedNotifier.value;
|
||
|
||
IconData get playModeIcon {
|
||
switch (_playMode) {
|
||
case PlayMode.sequential:
|
||
return Icons.repeat;
|
||
case PlayMode.repeatOne:
|
||
return Icons.repeat_one;
|
||
case PlayMode.shuffle:
|
||
return Icons.shuffle;
|
||
}
|
||
}
|
||
|
||
void setOnSongChanged(void Function(Song) callback) {
|
||
_onSongChanged = callback;
|
||
}
|
||
|
||
// ---- 切换播放模式(同步更新歌单) ----
|
||
void togglePlayMode() {
|
||
switch (_playMode) {
|
||
case PlayMode.sequential:
|
||
_playMode = PlayMode.repeatOne;
|
||
break;
|
||
case PlayMode.repeatOne:
|
||
_playMode = PlayMode.shuffle;
|
||
break;
|
||
case PlayMode.shuffle:
|
||
_playMode = PlayMode.sequential;
|
||
break;
|
||
}
|
||
notifyListeners();
|
||
|
||
// ⭐ 如果有当前歌单,同步更新歌单的播放模式
|
||
if (_currentPlaylistId != null) {
|
||
_playlistRepo.updatePlaylistPlayMode(_currentPlaylistId!, _playMode);
|
||
}
|
||
}
|
||
|
||
// ---- 设置播放队列 ----
|
||
void setQueue(List<Song> queue, {int startIndex = 0}) {
|
||
if (queue.isEmpty) {
|
||
_clearQueue();
|
||
return;
|
||
}
|
||
|
||
_queue = List.from(queue);
|
||
_currentIndex = startIndex.clamp(0, _queue.length - 1);
|
||
|
||
_shuffledIndices = List.generate(_queue.length, (i) => i);
|
||
_shuffledIndices.shuffle();
|
||
_shuffledIndex = _shuffledIndices.indexOf(_currentIndex);
|
||
if (_shuffledIndex == -1) {
|
||
_shuffledIndex = 0;
|
||
_currentIndex = _shuffledIndices[0];
|
||
}
|
||
|
||
_playCurrent();
|
||
}
|
||
|
||
void _clearQueue() {
|
||
_queue.clear();
|
||
_currentIndex = -1;
|
||
_shuffledIndices.clear();
|
||
_shuffledIndex = -1;
|
||
_currentPlaylistId = null;
|
||
stopPlay();
|
||
}
|
||
|
||
// ---- 播放指定歌曲 ----
|
||
Future<void> playSong(Song song) async {
|
||
// 播放单曲时清除歌单上下文
|
||
_currentPlaylistId = null;
|
||
if (_queue.isEmpty || _queue[_currentIndex].id != song.id) {
|
||
setQueue([song], startIndex: 0);
|
||
} else {
|
||
_playCurrent();
|
||
}
|
||
}
|
||
|
||
// ════════════════════════════════════════════════════════════
|
||
// 播放歌单
|
||
// ════════════════════════════════════════════════════════════
|
||
|
||
/// 播放整个歌单
|
||
Future<void> playPlaylist(String playlistId, {int startIndex = 0}) async {
|
||
_currentPlaylistId = playlistId;
|
||
|
||
// 1. 获取歌单的播放模式
|
||
final playlist = await _playlistRepo.getPlaylist(playlistId);
|
||
if (playlist != null) {
|
||
_playMode = playlist.playMode;
|
||
}
|
||
|
||
// 2. 获取歌单歌曲 ID 列表
|
||
final songIds = await _playlistRepo.getPlaylistSongIds(playlistId);
|
||
if (songIds.isEmpty) return;
|
||
|
||
// 3. 将 song_id 转换为 Song 对象
|
||
final songs = <Song>[];
|
||
for (final id in songIds) {
|
||
final dbSong = await _db.getSongByPath(id);
|
||
if (dbSong != null) {
|
||
songs.add(Song(
|
||
id: dbSong['remote_path'] as String,
|
||
title: dbSong['title'] as String? ?? '',
|
||
artist: dbSong['artist'] as String? ?? '未知艺术家',
|
||
url: dbSong['remote_path'] as String,
|
||
));
|
||
} else {
|
||
// 如果 songs 表中没有记录,用路径作为 fallback
|
||
songs.add(Song(
|
||
id: id,
|
||
title: id.split('/').last.replaceAll(RegExp(r'\.[^.]*$'), ''),
|
||
artist: '未知艺术家',
|
||
url: id,
|
||
));
|
||
}
|
||
}
|
||
|
||
if (songs.isNotEmpty) {
|
||
setQueue(songs, startIndex: startIndex);
|
||
}
|
||
}
|
||
|
||
/// 将当前播放队列保存为歌单
|
||
Future<Playlist> saveQueueAsPlaylist(String name) async {
|
||
// ⭐ 等待 createPlaylist 返回 Playlist 对象
|
||
final playlist = await _playlistRepo.createPlaylist(name);
|
||
for (int i = 0; i < _queue.length; i++) {
|
||
final song = _queue[i];
|
||
await _playlistRepo.addSong(playlist.id, song.id);
|
||
}
|
||
return playlist; // ⭐ 直接返回 Playlist 对象
|
||
}
|
||
|
||
// ════════════════════════════════════════════════════════════
|
||
// 播放核心
|
||
// ════════════════════════════════════════════════════════════
|
||
|
||
void _playCurrent() {
|
||
if (_currentIndex < 0 || _currentIndex >= _queue.length) {
|
||
stopPlay();
|
||
return;
|
||
}
|
||
|
||
_playbackGeneration++;
|
||
final generation = _playbackGeneration;
|
||
|
||
final song = _queue[_currentIndex];
|
||
_currentSong = song;
|
||
|
||
_startListening();
|
||
notifyListeners();
|
||
|
||
if (song.url == null || song.url!.isEmpty) {
|
||
return;
|
||
}
|
||
|
||
PlaybackService().play(song.url!);
|
||
|
||
_syncPlayerStateDelayed();
|
||
|
||
// ⭐ 立即推送基本信息(无 artwork)
|
||
_onSongChanged?.call(song);
|
||
|
||
// ⭐ 异步加载完整 metadata(含 artwork)
|
||
_loadMetadataForCurrentSong(generation);
|
||
}
|
||
|
||
String _generateSongKey(String url, int fileSize, int modifiedTime) {
|
||
final raw = '$url|$fileSize|$modifiedTime';
|
||
return raw.hashCode.toString();
|
||
}
|
||
|
||
Future<void> _loadMetadataForCurrentSong(int generation) async {
|
||
if (_currentIndex < 0 || _currentIndex >= _queue.length) return;
|
||
|
||
final currentIndex = _currentIndex;
|
||
final song = _queue[currentIndex];
|
||
final songId = song.id;
|
||
|
||
if (song.url == null || song.url!.isEmpty) {
|
||
_onSongChanged?.call(song);
|
||
return;
|
||
}
|
||
|
||
try {
|
||
final metadata = await MetadataService().getMetadata(
|
||
url: song.url!,
|
||
fileName: song.title,
|
||
fileId: song.id,
|
||
);
|
||
|
||
if (_playbackGeneration != generation) {
|
||
debugPrint('⚠️ [AudioService] metadata stale (generation), ignoring');
|
||
return;
|
||
}
|
||
if (_currentIndex != currentIndex) {
|
||
debugPrint(
|
||
'⚠️ [AudioService] metadata stale (index changed), ignoring');
|
||
return;
|
||
}
|
||
if (currentIndex >= _queue.length || _queue[currentIndex].id != songId) {
|
||
debugPrint('⚠️ [AudioService] metadata stale (song changed), ignoring');
|
||
return;
|
||
}
|
||
|
||
final updatedSong = Song(
|
||
id: song.id,
|
||
title: metadata.title.isNotEmpty ? metadata.title : song.title,
|
||
artist: metadata.artist.isNotEmpty ? metadata.artist : song.artist,
|
||
url: song.url,
|
||
artwork: metadata.artwork,
|
||
);
|
||
_queue[_currentIndex] = updatedSong;
|
||
_currentSong = updatedSong;
|
||
notifyListeners();
|
||
|
||
_onSongChanged?.call(updatedSong);
|
||
debugPrint(
|
||
'✅ [AudioService] metadata updated: ${updatedSong.title} - ${updatedSong.artist} (generation $generation)');
|
||
} catch (e) {
|
||
debugPrint('⚠️ [AudioService] metadata load failed: $e, using fallback');
|
||
_onSongChanged?.call(song);
|
||
}
|
||
}
|
||
|
||
/// 清除当前歌曲的缓存
|
||
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}');
|
||
|
||
final currentIndex = _currentIndex;
|
||
|
||
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();
|
||
}
|
||
|
||
final db = SongDatabase();
|
||
await db.deleteSong(songKey);
|
||
await db.deleteCache(songKey);
|
||
debugPrint('🗑️ [AudioService] SQLite records deleted: $songKey');
|
||
|
||
await ArtworkHelper.deleteArtwork(songKey);
|
||
debugPrint('🗑️ [AudioService] artwork deleted');
|
||
|
||
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) {
|
||
// 忽略
|
||
}
|
||
|
||
await MetadataService().clearCache(song.id);
|
||
debugPrint('🗑️ [AudioService] memory cache cleared');
|
||
|
||
if (currentIndex >= 0 && currentIndex < _queue.length) {
|
||
stopPlay();
|
||
_playCurrent();
|
||
debugPrint('🔄 [AudioService] song reloaded');
|
||
}
|
||
}
|
||
|
||
// ---- 下一首 ----
|
||
void next() {
|
||
if (_queue.isEmpty) return;
|
||
|
||
if (_playMode == PlayMode.shuffle) {
|
||
if (_shuffledIndices.isEmpty) return;
|
||
final nextIdx = (_shuffledIndex + 1) % _shuffledIndices.length;
|
||
_shuffledIndex = nextIdx;
|
||
_currentIndex = _shuffledIndices[nextIdx];
|
||
_playCurrent();
|
||
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;
|
||
if (prevIdx < 0) {
|
||
_shuffledIndex = _shuffledIndices.length - 1;
|
||
} else {
|
||
_shuffledIndex = prevIdx;
|
||
}
|
||
_currentIndex = _shuffledIndices[_shuffledIndex];
|
||
_playCurrent();
|
||
return;
|
||
}
|
||
|
||
final prevIdx = (_currentIndex - 1) % _queue.length;
|
||
if (prevIdx < 0) {
|
||
_currentIndex = _queue.length - 1;
|
||
} else {
|
||
_currentIndex = prevIdx;
|
||
}
|
||
_playCurrent();
|
||
}
|
||
|
||
// ---- 播放/暂停 ----
|
||
void togglePlay() {
|
||
if (_currentSong == null) return;
|
||
|
||
if (_isPlaying) {
|
||
PlaybackService().pause();
|
||
} else {
|
||
PlaybackService().resume();
|
||
}
|
||
}
|
||
|
||
void stopPlay() {
|
||
_currentSong = null;
|
||
_isPlaying = false;
|
||
positionNotifier.value = Duration.zero;
|
||
durationNotifier.value = Duration.zero;
|
||
bufferedNotifier.value = Duration.zero;
|
||
_stopListening();
|
||
notifyListeners();
|
||
}
|
||
|
||
void seekTo(Duration position) {
|
||
_isUserSeeking = true;
|
||
PlaybackService().seek(position);
|
||
positionNotifier.value = position;
|
||
|
||
Future.delayed(const Duration(milliseconds: 800), () {
|
||
_isUserSeeking = false;
|
||
});
|
||
}
|
||
|
||
void clearQueue() {
|
||
_queue.clear();
|
||
_currentIndex = -1;
|
||
_shuffledIndices.clear();
|
||
_shuffledIndex = -1;
|
||
_currentPlaylistId = null;
|
||
stopPlay();
|
||
notifyListeners();
|
||
}
|
||
|
||
void syncPlayerStateNow() {
|
||
final player = PlaybackService().player;
|
||
final pos = player.state.position;
|
||
final dur = player.state.duration;
|
||
final buf = player.state.buffer;
|
||
|
||
debugPrint(
|
||
'🎯 [AudioService] syncPlayerStateNow: pos=$pos, dur=$dur, buf=$buf');
|
||
|
||
if (pos.inMilliseconds >= 0) {
|
||
positionNotifier.value = pos;
|
||
}
|
||
if (dur.inMilliseconds > 0) {
|
||
durationNotifier.value = dur;
|
||
}
|
||
if (buf.inMilliseconds >= 0) {
|
||
bufferedNotifier.value = buf;
|
||
}
|
||
}
|
||
|
||
void _syncPlayerStateDelayed() {
|
||
syncPlayerStateNow();
|
||
Future.delayed(const Duration(milliseconds: 200), () {
|
||
syncPlayerStateNow();
|
||
});
|
||
Future.delayed(const Duration(milliseconds: 500), () {
|
||
syncPlayerStateNow();
|
||
});
|
||
}
|
||
|
||
void _startListening() {
|
||
if (_listening) return;
|
||
_listening = true;
|
||
|
||
final player = PlaybackService().player;
|
||
|
||
_subscriptions.add(
|
||
player.stream.playing.listen((playing) {
|
||
if (_isPlaying != playing) {
|
||
_isPlaying = playing;
|
||
notifyListeners();
|
||
}
|
||
}),
|
||
);
|
||
|
||
_subscriptions.add(
|
||
player.stream.position.listen((position) {
|
||
if (_isUserSeeking) {
|
||
debugPrint('🎯 [AudioService] positionStream ignored: user seeking');
|
||
return;
|
||
}
|
||
positionNotifier.value = position;
|
||
}),
|
||
);
|
||
|
||
_subscriptions.add(
|
||
player.stream.duration.listen((duration) {
|
||
debugPrint('🎯 [AudioService] durationStream: $duration');
|
||
if (duration.inMilliseconds > 0) {
|
||
durationNotifier.value = duration;
|
||
}
|
||
}),
|
||
);
|
||
|
||
_subscriptions.add(
|
||
player.stream.buffer.listen((buffer) {
|
||
bufferedNotifier.value = buffer;
|
||
}),
|
||
);
|
||
|
||
_subscriptions.add(
|
||
player.stream.completed.listen((_) {
|
||
_onPlaybackCompleted();
|
||
}),
|
||
);
|
||
}
|
||
|
||
void _stopListening() {
|
||
_listening = false;
|
||
for (final subscription in _subscriptions) {
|
||
subscription.cancel();
|
||
}
|
||
_subscriptions.clear();
|
||
}
|
||
|
||
void _onPlaybackCompleted() {
|
||
if (_handlingCompletion) {
|
||
debugPrint('⚠️ [service] completed ignored: already handling');
|
||
return;
|
||
}
|
||
_handlingCompletion = true;
|
||
try {
|
||
if (_queue.isEmpty) return;
|
||
if (_playMode == PlayMode.repeatOne) {
|
||
_playCurrent();
|
||
return;
|
||
}
|
||
next();
|
||
} finally {
|
||
_handlingCompletion = false;
|
||
}
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
_stopListening();
|
||
positionNotifier.dispose();
|
||
durationNotifier.dispose();
|
||
bufferedNotifier.dispose();
|
||
PlaybackService().dispose();
|
||
super.dispose();
|
||
}
|
||
}
|