Files
minstrel/flutter_client/lib/player/audio_handler.dart
T
bvandeusen 2499449c0b feat(flutter/player): playNext + enqueue + PlaylistsApi.appendTracks
Three small data-layer additions for the upcoming track-actions menu:

- PlaylistsApi.appendTracks(playlistId, trackIds) wraps
  POST /api/playlists/{id}/tracks for the "Add to playlist" action.
- audio_handler gains playNext (insertAudioSource at currentIndex+1)
  and enqueue (addAudioSource) — both also push the audio_service
  queue notifier so the queue-screen UI stays in sync.
- The AudioSource construction was extracted into a private
  _buildAudioSource helper so setQueueFromTracks / playNext / enqueue
  share one source-building path.
- PlayerActions exposes playNext / enqueue for menu use.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:40:17 -04:00

186 lines
6.3 KiB
Dart

import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:flutter/foundation.dart';
import 'package:just_audio/just_audio.dart';
import '../models/track.dart';
import 'album_cover_cache.dart';
class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
MinstrelAudioHandler() {
_player.playbackEventStream.listen(_broadcastState);
_player.currentIndexStream.listen(_onCurrentIndexChanged);
}
final AudioPlayer _player = AudioPlayer();
String _baseUrl = '';
String? _token;
AlbumCoverCache? _coverCache;
void configure({
required String baseUrl,
required String? token,
AlbumCoverCache? coverCache,
}) {
_baseUrl = baseUrl;
_token = token;
if (coverCache != null) _coverCache = coverCache;
debugPrint('audio_handler.configure: baseUrl="$baseUrl" '
'tokenPresent=${token != null && token.isNotEmpty} '
'cachePresent=${_coverCache != null}');
}
Future<void> setQueueFromTracks(List<TrackRef> tracks, {int initialIndex = 0}) async {
final items = tracks.map(_toMediaItem).toList();
queue.add(items);
if (items.isNotEmpty) {
mediaItem.add(items[initialIndex.clamp(0, items.length - 1)]);
}
debugPrint('audio_handler.setQueueFromTracks: '
'_baseUrl="$_baseUrl" trackCount=${tracks.length}');
final sources = tracks.map(_buildAudioSource).toList();
await _player.setAudioSources(
sources,
initialIndex: initialIndex,
);
// Kick the cover fetch for the initial item — async, doesn't block
// playback. Subsequent track changes are handled by the
// currentIndexStream listener.
unawaited(_loadArtForCurrentItem());
}
String _resolveStreamUrl(TrackRef t) {
if (t.streamUrl.isEmpty) {
return '$_baseUrl/api/tracks/${t.id}/stream';
}
final parsed = Uri.tryParse(t.streamUrl);
if (parsed != null && parsed.hasScheme) {
return t.streamUrl;
}
return '$_baseUrl${t.streamUrl}';
}
/// Builds a single AudioSource for a track, applying URL resolution
/// against _baseUrl and attaching the Bearer header. Throws StateError
/// if the resolved URL is scheme-less (which would otherwise crash
/// ExoPlayer with a confusing localhost cleartext error).
AudioSource _buildAudioSource(TrackRef t) {
final headers = _token == null ? null : {'Authorization': 'Bearer $_token'};
final url = _resolveStreamUrl(t);
debugPrint('audio_handler: track.id=${t.id} '
'track.streamUrl="${t.streamUrl}" → resolved="$url"');
final parsed = Uri.parse(url);
if (!parsed.hasScheme || parsed.host.isEmpty) {
throw StateError(
'audio_handler: refused to play scheme-less URL "$url" '
'(baseUrl="$_baseUrl", track.streamUrl="${t.streamUrl}", '
'track.id="${t.id}"). configure() must be called with a '
'non-empty baseUrl before setQueueFromTracks().',
);
}
return AudioSource.uri(parsed, headers: headers);
}
/// Inserts [track] right after the currently-playing item so it plays
/// next. If nothing is playing, appends to the end.
Future<void> playNext(TrackRef track) async {
final source = _buildAudioSource(track);
final item = _toMediaItem(track);
final currentIdx = _player.currentIndex;
final insertAt = currentIdx == null ? queue.value.length : currentIdx + 1;
await _player.insertAudioSource(insertAt, source);
final current = queue.value;
queue.add([
...current.sublist(0, insertAt),
item,
...current.sublist(insertAt),
]);
}
/// Appends [track] to the end of the queue.
Future<void> enqueue(TrackRef track) async {
final source = _buildAudioSource(track);
final item = _toMediaItem(track);
await _player.addAudioSource(source);
queue.add([...queue.value, item]);
}
MediaItem _toMediaItem(TrackRef t) => MediaItem(
id: t.id,
title: t.title,
artist: t.artistName,
album: t.albumTitle,
duration: Duration(seconds: t.durationSec),
// Stash album_id in extras so _loadArtForCurrentItem can pull it
// back without re-walking the track list.
extras: t.albumId.isEmpty ? null : {'album_id': t.albumId},
);
void _onCurrentIndexChanged(int? idx) {
if (idx == null) return;
unawaited(_loadArtForCurrentItem());
}
/// Async-fetches the cover for whichever item is currently active and
/// pushes a MediaItem update with artUri set. No-op if no cache is
/// configured, no current item, the item has no album_id in extras,
/// or the fetch returns null.
Future<void> _loadArtForCurrentItem() async {
final cache = _coverCache;
if (cache == null) return;
final current = mediaItem.value;
if (current == null) return;
final albumId = current.extras?['album_id'] as String?;
if (albumId == null || albumId.isEmpty) return;
if (current.artUri != null) return; // already set
final path = await cache.getOrFetch(albumId);
if (path == null) return;
// Discard if the user advanced to another track while we waited.
if (mediaItem.value?.id != current.id) return;
mediaItem.add(current.copyWith(artUri: Uri.file(path)));
}
@override
Future<void> play() => _player.play();
@override
Future<void> pause() => _player.pause();
@override
Future<void> seek(Duration position) => _player.seek(position);
@override
Future<void> skipToNext() => _player.seekToNext();
@override
Future<void> skipToPrevious() => _player.seekToPrevious();
void _broadcastState(PlaybackEvent event) {
final playing = _player.playing;
playbackState.add(PlaybackState(
controls: [
MediaControl.skipToPrevious,
if (playing) MediaControl.pause else MediaControl.play,
MediaControl.skipToNext,
],
systemActions: const {MediaAction.seek},
processingState: switch (_player.processingState) {
ProcessingState.idle => AudioProcessingState.idle,
ProcessingState.loading => AudioProcessingState.loading,
ProcessingState.buffering => AudioProcessingState.buffering,
ProcessingState.ready => AudioProcessingState.ready,
ProcessingState.completed => AudioProcessingState.completed,
},
playing: playing,
updatePosition: _player.position,
bufferedPosition: _player.bufferedPosition,
speed: _player.speed,
queueIndex: event.currentIndex,
));
}
}