1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
|
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
// ---------------------------------------------------------------------------
// PlayerAudioHandler
// ---------------------------------------------------------------------------
/// [BaseAudioHandler] subclass that wraps a [just_audio] [AudioPlayer] and
/// bridges it to the Android media-session / iOS AVAudioSession so that:
/// - Playback continues in the background as a foreground service.
/// - Lock-screen and notification controls (play/pause/seek/skip) work.
/// - Audio focus is honoured: playback pauses on phone calls or other
/// audio interruptions and resumes when focus is regained.
/// - Bluetooth headset media buttons (play, pause, next, previous) are
/// forwarded by [AudioService] and handled here.
///
/// Single Responsibility: this class only translates between the
/// [BaseAudioHandler] protocol and [AudioPlayer]'s API. All progress
/// reporting and navigation logic lives in [AudioPlayerScreen].
///
/// The handler is registered once via [AudioService.init] in [main].
/// Consumers retrieve the singleton through [audioHandlerProvider].
class PlayerAudioHandler extends BaseAudioHandler with SeekHandler {
/// Creates the handler with an already-configured [AudioPlayer].
///
/// The player is injected so that tests can supply a mock without any
/// platform channels (Dependency Inversion Principle).
PlayerAudioHandler(this._player) {
// Propagate just_audio's playback state into the audio_service stream so
// the notification, lock screen, and Wear OS clients see live updates.
_player.playbackEventStream.listen(_onPlaybackEvent);
// Propagate playing/paused transitions, which are not always carried in
// playback events (just_audio emits them separately).
_player.playingStream.listen((_) => _broadcastState());
// Propagate processing-state changes (e.g. loading → ready → completed).
_player.processingStateStream.listen((_) => _broadcastState());
}
final AudioPlayer _player;
// ---------------------------------------------------------------------------
// Public accessors (used by AudioPlayerScreen to avoid a second Player)
// ---------------------------------------------------------------------------
/// The underlying [AudioPlayer] so the screen can subscribe to position /
/// duration streams and still use bearer-token authenticated sources.
///
/// Exposing the player directly is intentional: [AudioPlayerScreen] owns the
/// progress-sync timer and needs raw position/duration access. No extra
/// abstraction layer is needed here (YAGNI).
AudioPlayer get player => _player;
// ---------------------------------------------------------------------------
// BaseAudioHandler — playback controls
// ---------------------------------------------------------------------------
@override
Future<void> play() => _player.play();
@override
Future<void> pause() => _player.pause();
@override
Future<void> stop() async {
await _player.stop();
await super.stop();
}
/// Seeks to [position] within the current item.
///
/// [SeekHandler] mixin provides the default [fastForward] / [rewind]
/// implementations in terms of this method.
@override
Future<void> seek(Duration position) => _player.seek(position);
/// Skip forward 15 seconds (media-button "next" maps to a short skip for
/// podcast and audiobook use-cases rather than a full track change).
@override
Future<void> skipToNext() async {
final current = _player.position;
final total = _player.duration ?? Duration.zero;
final next = _clamp(current + const Duration(seconds: 15), Duration.zero, total);
await _player.seek(next);
}
/// Skip back 15 seconds.
@override
Future<void> skipToPrevious() async {
final current = _player.position;
final total = _player.duration ?? Duration.zero;
final prev = _clamp(current - const Duration(seconds: 15), Duration.zero, total);
await _player.seek(prev);
}
/// Changes playback speed and refreshes the notification state.
@override
Future<void> setSpeed(double speed) async {
await _player.setSpeed(speed);
_broadcastState();
}
// ---------------------------------------------------------------------------
// Media item helpers (called by AudioPlayerScreen after player is ready)
// ---------------------------------------------------------------------------
/// Pushes a new [MediaItem] onto the [mediaItem] stream so the Android media
/// notification and lock-screen controls show the correct title and duration.
///
/// Named [setMediaItem] rather than [updateMediaItem] to avoid clashing with
/// [BaseAudioHandler.updateMediaItem] (which takes a full [MediaItem] and
/// notifies children in a queue scenario — not applicable here).
///
/// Called once per session after the player finishes loading the source.
void setMediaItem({required String id, required String title}) {
mediaItem.add(
MediaItem(
id: id,
title: title,
duration: _player.duration,
),
);
}
// ---------------------------------------------------------------------------
// Internal — state broadcast
// ---------------------------------------------------------------------------
/// Converts [just_audio]'s [PlaybackEvent] into [audio_service]'s
/// [PlaybackState] and pushes it onto the [playbackState] stream.
///
/// Called on every playback event so the notification and lock-screen
/// controls always reflect the true player state.
void _onPlaybackEvent(PlaybackEvent event) => _broadcastState();
/// Emits the current [PlaybackState] derived from the underlying player.
///
/// Maps [just_audio]'s processing state to [audio_service]'s equivalents and
/// advertises which controls are enabled so Android can render the correct
/// notification buttons.
void _broadcastState() {
final processingState = _mapProcessingState(_player.processingState);
playbackState.add(
PlaybackState(
// Advertise all supported actions so the notification, lock screen,
// and Bluetooth headset buttons all get the correct controls.
controls: [
MediaControl.skipToPrevious, // maps to skipToPrevious (–15 s)
if (_player.playing) MediaControl.pause else MediaControl.play,
MediaControl.stop,
MediaControl.skipToNext, // maps to skipToNext (+15 s)
],
systemActions: const {
MediaAction.seek,
MediaAction.seekForward,
MediaAction.seekBackward,
},
androidCompactActionIndices: const [0, 1, 3], // prev, play/pause, next
processingState: processingState,
playing: _player.playing,
updatePosition: _player.position,
bufferedPosition: _player.bufferedPosition,
speed: _player.speed,
),
);
}
/// Translates [just_audio]'s [ProcessingState] to [audio_service]'s
/// [AudioProcessingState] so the notification can show loading spinners.
AudioProcessingState _mapProcessingState(ProcessingState state) {
switch (state) {
case ProcessingState.idle:
return AudioProcessingState.idle;
case ProcessingState.loading:
return AudioProcessingState.loading;
case ProcessingState.buffering:
return AudioProcessingState.buffering;
case ProcessingState.ready:
return AudioProcessingState.ready;
case ProcessingState.completed:
return AudioProcessingState.completed;
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/// Clamps [value] to [[min], [max]]; [Duration] doesn't implement [Comparable]
/// so we do the comparison manually (mirrors VideoPlayerScreen pattern).
Duration _clamp(Duration value, Duration min, Duration max) {
if (value < min) return min;
if (max > Duration.zero && value > max) return max;
return value;
}
}
|