refactors design to flutter driven service core.
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:audio_session/audio_session.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
|
||||
import 'live_info_business_object.dart';
|
||||
|
||||
class KryzAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
KryzAudioHandler() {
|
||||
mediaItem.add(_defaultMediaItem);
|
||||
_playerStateSubscription = _player.playerStateStream.listen(
|
||||
_onPlayerStateChanged,
|
||||
);
|
||||
}
|
||||
|
||||
static const String streamUrl = 'https://kryz.out.airtime.pro/kryz_a';
|
||||
static const String mediaId = 'kryz-live-stream';
|
||||
static const String _liveInfoEndpoint = 'http://kryz.airtime.pro/api/live-info';
|
||||
static const Duration _liveInfoTimeout = Duration(seconds: 8);
|
||||
static const Duration _metadataRefreshInterval = Duration(seconds: 20);
|
||||
|
||||
static const MediaItem _defaultMediaItem = MediaItem(
|
||||
id: mediaId,
|
||||
title: 'KRYZ Live Stream',
|
||||
artist: 'KRYZ Radio',
|
||||
album: 'Live',
|
||||
extras: <String, dynamic>{
|
||||
'isLive': true,
|
||||
'seekable': false,
|
||||
},
|
||||
);
|
||||
|
||||
final AudioPlayer _player = AudioPlayer();
|
||||
late final StreamSubscription<PlayerState> _playerStateSubscription;
|
||||
Timer? _metadataRefreshTimer;
|
||||
bool _isAudioSessionConfigured = false;
|
||||
bool _isSourceLoaded = false;
|
||||
bool _playRequested = false;
|
||||
|
||||
Future<void> updateMetadataFromLiveInfo(LiveInfoSnapshot? snapshot) async {
|
||||
final current = snapshot?.current;
|
||||
if (current == null || current.type != 'track') {
|
||||
mediaItem.add(_defaultMediaItem);
|
||||
return;
|
||||
}
|
||||
|
||||
final String subtitle = current.displaySubtitle.trim();
|
||||
mediaItem.add(
|
||||
MediaItem(
|
||||
id: mediaId,
|
||||
title: current.displayTitle,
|
||||
artist: subtitle.isEmpty ? 'KRYZ Radio' : subtitle,
|
||||
album: 'Live',
|
||||
extras: <String, dynamic>{
|
||||
'isLive': true,
|
||||
'seekable': false,
|
||||
'starts': current.starts,
|
||||
'ends': current.ends,
|
||||
'schedulerTime': snapshot?.schedulerTime,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> play() async {
|
||||
_playRequested = true;
|
||||
playbackState.add(
|
||||
playbackState.value.copyWith(
|
||||
controls: const <MediaControl>[MediaControl.stop],
|
||||
systemActions: const <MediaAction>{},
|
||||
processingState: AudioProcessingState.buffering,
|
||||
playing: false,
|
||||
),
|
||||
);
|
||||
|
||||
await _configureAudioSessionIfNeeded();
|
||||
|
||||
try {
|
||||
if (!_isSourceLoaded) {
|
||||
await _player.setAudioSource(
|
||||
AudioSource.uri(
|
||||
Uri.parse(streamUrl),
|
||||
tag: mediaItem.value,
|
||||
),
|
||||
);
|
||||
_isSourceLoaded = true;
|
||||
}
|
||||
|
||||
final session = await AudioSession.instance;
|
||||
await session.setActive(true);
|
||||
await _player.play();
|
||||
await _refreshMetadataFromApi();
|
||||
_startMetadataRefreshTimer();
|
||||
} catch (_) {
|
||||
_playRequested = false;
|
||||
playbackState.add(
|
||||
playbackState.value.copyWith(
|
||||
controls: const <MediaControl>[MediaControl.play],
|
||||
systemActions: const <MediaAction>{},
|
||||
processingState: AudioProcessingState.idle,
|
||||
playing: false,
|
||||
),
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stop() async {
|
||||
_playRequested = false;
|
||||
_isSourceLoaded = false;
|
||||
_metadataRefreshTimer?.cancel();
|
||||
_metadataRefreshTimer = null;
|
||||
await _player.stop();
|
||||
playbackState.add(
|
||||
playbackState.value.copyWith(
|
||||
controls: const <MediaControl>[MediaControl.play],
|
||||
systemActions: const <MediaAction>{},
|
||||
processingState: AudioProcessingState.idle,
|
||||
playing: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> seek(Duration position) async {
|
||||
// Live stream is intentionally non-seekable.
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> playFromMediaId(String mediaId, [Map<String, dynamic>? extras]) {
|
||||
return play();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> playFromSearch(String query, [Map<String, dynamic>? extras]) {
|
||||
return play();
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
_metadataRefreshTimer?.cancel();
|
||||
await _playerStateSubscription.cancel();
|
||||
await _player.dispose();
|
||||
}
|
||||
|
||||
Future<void> _configureAudioSessionIfNeeded() async {
|
||||
if (_isAudioSessionConfigured) {
|
||||
return;
|
||||
}
|
||||
|
||||
final session = await AudioSession.instance;
|
||||
await session.configure(const AudioSessionConfiguration.music());
|
||||
_isAudioSessionConfigured = true;
|
||||
}
|
||||
|
||||
void _onPlayerStateChanged(PlayerState state) {
|
||||
final AudioProcessingState processingState = switch (state.processingState) {
|
||||
ProcessingState.idle => AudioProcessingState.idle,
|
||||
ProcessingState.loading => AudioProcessingState.loading,
|
||||
ProcessingState.buffering => AudioProcessingState.buffering,
|
||||
ProcessingState.ready => AudioProcessingState.ready,
|
||||
ProcessingState.completed => AudioProcessingState.completed,
|
||||
};
|
||||
|
||||
final bool isPlaying = state.playing && state.processingState == ProcessingState.ready;
|
||||
final bool isBuffering = (state.playing && state.processingState != ProcessingState.ready) ||
|
||||
(_playRequested && !state.playing && state.processingState != ProcessingState.completed);
|
||||
|
||||
playbackState.add(
|
||||
playbackState.value.copyWith(
|
||||
controls: <MediaControl>[
|
||||
if (isPlaying || isBuffering) MediaControl.stop else MediaControl.play,
|
||||
],
|
||||
systemActions: const <MediaAction>{},
|
||||
processingState: isBuffering ? AudioProcessingState.buffering : processingState,
|
||||
playing: isPlaying,
|
||||
),
|
||||
);
|
||||
|
||||
if (isPlaying || isBuffering) {
|
||||
_startMetadataRefreshTimer();
|
||||
} else {
|
||||
_metadataRefreshTimer?.cancel();
|
||||
_metadataRefreshTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
void _startMetadataRefreshTimer() {
|
||||
if (_metadataRefreshTimer != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
_metadataRefreshTimer = Timer.periodic(_metadataRefreshInterval, (_) {
|
||||
_refreshMetadataFromApi();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _refreshMetadataFromApi() async {
|
||||
try {
|
||||
final response = await http
|
||||
.get(Uri.parse(_liveInfoEndpoint))
|
||||
.timeout(_liveInfoTimeout);
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
return;
|
||||
}
|
||||
|
||||
final dynamic decoded = jsonDecode(response.body);
|
||||
if (decoded is! Map<String, dynamic>) {
|
||||
return;
|
||||
}
|
||||
|
||||
final snapshot = LiveInfoSnapshot.fromJson(decoded);
|
||||
await updateMetadataFromLiveInfo(snapshot);
|
||||
} catch (_) {
|
||||
// Keep existing metadata if live-info fetch fails.
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-25
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:just_audio_background/just_audio_background.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:timezone/data/latest.dart' as tz;
|
||||
import 'app_theme_business_object.dart';
|
||||
@@ -12,13 +13,7 @@ import 'streaming_audio_business_object.dart';
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
tz.initializeTimeZones();
|
||||
await JustAudioBackground.init(
|
||||
androidNotificationChannelId: 'com.kryzgoflutter.audio.channel',
|
||||
androidNotificationChannelName: 'KRYZ Audio Playback',
|
||||
androidNotificationOngoing: true,
|
||||
);
|
||||
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
unawaited(StreamingAudioBusinessObject.initializeBackgroundAudio());
|
||||
await SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.portraitUp,
|
||||
DeviceOrientation.portraitDown,
|
||||
@@ -139,11 +134,6 @@ class _MainPageState extends State<MainPage> {
|
||||
_liveInfo.addListener(_handleLiveInfoChanged);
|
||||
_liveInfo.start();
|
||||
_playbackChannel.setMethodCallHandler(_handlePlaybackMethodCall);
|
||||
// Tell native that Flutter is ready to receive method calls.
|
||||
// On Android this unblocks any pending auto_play from Android Auto.
|
||||
if (defaultTargetPlatform == TargetPlatform.android) {
|
||||
_playbackChannel.invokeMethod<void>('flutterReady');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handlePlaybackMethodCall(MethodCall call) async {
|
||||
@@ -163,19 +153,11 @@ class _MainPageState extends State<MainPage> {
|
||||
setState(() {
|
||||
// Rebuild when playback state changes from the player.
|
||||
});
|
||||
|
||||
_syncAutoPlaybackState();
|
||||
}
|
||||
|
||||
void _syncAutoPlaybackState() {
|
||||
if (defaultTargetPlatform != TargetPlatform.android) return;
|
||||
_playbackChannel.invokeMethod<void>('updatePlaybackState', {
|
||||
'isPlaying': _audio.isPlaying,
|
||||
'isBuffering': _audio.isBuffering,
|
||||
});
|
||||
}
|
||||
|
||||
void _handleLiveInfoChanged() {
|
||||
_audio.updateMetadataFromLiveInfo(_liveInfo.snapshot);
|
||||
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
@@ -213,8 +195,8 @@ class _MainPageState extends State<MainPage> {
|
||||
try {
|
||||
await _casting.startCastingLiveStream(
|
||||
streamUrl: _audio.streamUrl,
|
||||
title: 'KRYZ Live Stream',
|
||||
subtitle: 'KRYZ Radio',
|
||||
title: _audio.currentTitle,
|
||||
subtitle: _audio.currentSubtitle,
|
||||
);
|
||||
|
||||
_castStreamStartedForActiveSession = true;
|
||||
|
||||
@@ -1,48 +1,94 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:audio_session/audio_session.dart';
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:just_audio_background/just_audio_background.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
|
||||
import 'kryz_audio_handler.dart';
|
||||
import 'live_info_business_object.dart';
|
||||
|
||||
enum StreamingPlaybackStatus { stopped, buffering, playing }
|
||||
|
||||
class StreamingAudioBusinessObject extends ChangeNotifier {
|
||||
StreamingAudioBusinessObject({
|
||||
this.streamUrl = 'https://kryz.out.airtime.pro/kryz_a',
|
||||
}) {
|
||||
_playerStateSubscription = _player.playerStateStream.listen((state) {
|
||||
_setPlaybackStatus(_mapPlayerStateToStatus(state));
|
||||
});
|
||||
StreamingAudioBusinessObject() {
|
||||
if (_audioHandler == null && _audioHandlerInitFuture == null) {
|
||||
initializeBackgroundAudio();
|
||||
}
|
||||
|
||||
final initFuture = _audioHandlerInitFuture;
|
||||
if (initFuture != null) {
|
||||
initFuture.then((handler) {
|
||||
if (_isDisposed) {
|
||||
return;
|
||||
}
|
||||
_attachHandler(handler);
|
||||
});
|
||||
}
|
||||
|
||||
final handler = _audioHandler;
|
||||
if (handler != null) {
|
||||
_attachHandler(handler);
|
||||
}
|
||||
}
|
||||
|
||||
final String streamUrl;
|
||||
final AudioPlayer _player = AudioPlayer();
|
||||
late final StreamSubscription<PlayerState> _playerStateSubscription;
|
||||
bool _isSourceLoaded = false;
|
||||
static AudioHandler? _audioHandler;
|
||||
static Future<AudioHandler>? _audioHandlerInitFuture;
|
||||
|
||||
static Future<void> initializeBackgroundAudio() async {
|
||||
if (_audioHandler != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
_audioHandlerInitFuture ??= AudioService.init(
|
||||
builder: () => KryzAudioHandler(),
|
||||
config: const AudioServiceConfig(
|
||||
androidNotificationChannelId: 'com.kryzgoflutter.audio.channel',
|
||||
androidNotificationChannelName: 'KRYZ Audio Playback',
|
||||
androidNotificationOngoing: true,
|
||||
androidStopForegroundOnPause: true,
|
||||
),
|
||||
).then((handler) {
|
||||
_audioHandler = handler;
|
||||
return handler;
|
||||
}).catchError((error) {
|
||||
_audioHandlerInitFuture = null;
|
||||
throw error;
|
||||
});
|
||||
|
||||
await _audioHandlerInitFuture;
|
||||
}
|
||||
|
||||
String get streamUrl => KryzAudioHandler.streamUrl;
|
||||
|
||||
StreamSubscription<PlaybackState>? _playbackStateSubscription;
|
||||
StreamSubscription<MediaItem?>? _mediaItemSubscription;
|
||||
StreamingPlaybackStatus _playbackStatus = StreamingPlaybackStatus.stopped;
|
||||
bool _isAudioSessionConfigured = false;
|
||||
bool _playRequested = false;
|
||||
bool _isDisposed = false;
|
||||
bool _isAttached = false;
|
||||
String _currentTitle = 'KRYZ Live Stream';
|
||||
String _currentSubtitle = 'KRYZ Radio';
|
||||
|
||||
StreamingPlaybackStatus get playbackStatus => _playbackStatus;
|
||||
bool get isPlaying => _playbackStatus == StreamingPlaybackStatus.playing;
|
||||
bool get isBuffering => _playbackStatus == StreamingPlaybackStatus.buffering;
|
||||
bool get isStopped => _playbackStatus == StreamingPlaybackStatus.stopped;
|
||||
String get currentTitle => _currentTitle;
|
||||
String get currentSubtitle => _currentSubtitle;
|
||||
|
||||
StreamingPlaybackStatus _mapPlayerStateToStatus(PlayerState state) {
|
||||
if (state.processingState == ProcessingState.completed) {
|
||||
StreamingPlaybackStatus _mapPlaybackStateToStatus(PlaybackState state) {
|
||||
if (state.processingState == AudioProcessingState.completed) {
|
||||
return StreamingPlaybackStatus.stopped;
|
||||
}
|
||||
|
||||
if (state.playing) {
|
||||
if (state.processingState == ProcessingState.ready) {
|
||||
if (state.processingState == AudioProcessingState.ready) {
|
||||
return StreamingPlaybackStatus.playing;
|
||||
}
|
||||
|
||||
return StreamingPlaybackStatus.buffering;
|
||||
}
|
||||
|
||||
if (_playRequested && state.processingState != ProcessingState.completed) {
|
||||
if (state.processingState == AudioProcessingState.buffering ||
|
||||
state.processingState == AudioProcessingState.loading) {
|
||||
return StreamingPlaybackStatus.buffering;
|
||||
}
|
||||
|
||||
@@ -58,58 +104,66 @@ class StreamingAudioBusinessObject extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _configureAudioSessionIfNeeded() async {
|
||||
if (_isAudioSessionConfigured) {
|
||||
return;
|
||||
}
|
||||
|
||||
final session = await AudioSession.instance;
|
||||
await session.configure(const AudioSessionConfiguration.music());
|
||||
_isAudioSessionConfigured = true;
|
||||
}
|
||||
|
||||
Future<void> play() async {
|
||||
_playRequested = true;
|
||||
await _configureAudioSessionIfNeeded();
|
||||
_setPlaybackStatus(StreamingPlaybackStatus.buffering);
|
||||
|
||||
try {
|
||||
if (!_isSourceLoaded) {
|
||||
await _player.setAudioSource(
|
||||
AudioSource.uri(
|
||||
Uri.parse(streamUrl),
|
||||
tag: const MediaItem(
|
||||
id: 'kryz-live-stream',
|
||||
title: 'KRYZ Live Stream',
|
||||
artist: 'KRYZ Radio',
|
||||
album: 'Live',
|
||||
),
|
||||
),
|
||||
);
|
||||
_isSourceLoaded = true;
|
||||
}
|
||||
|
||||
final session = await AudioSession.instance;
|
||||
await session.setActive(true);
|
||||
await _player.play();
|
||||
} catch (_) {
|
||||
_playRequested = false;
|
||||
_setPlaybackStatus(StreamingPlaybackStatus.stopped);
|
||||
rethrow;
|
||||
}
|
||||
final handler = await _requireHandler();
|
||||
await handler.play();
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
_playRequested = false;
|
||||
_isSourceLoaded = false;
|
||||
final handler = await _requireHandler();
|
||||
await handler.stop();
|
||||
_setPlaybackStatus(StreamingPlaybackStatus.stopped);
|
||||
await _player.stop();
|
||||
}
|
||||
|
||||
Future<void> updateMetadataFromLiveInfo(LiveInfoSnapshot? snapshot) async {
|
||||
final handler = await _requireHandler();
|
||||
await handler.updateMetadataFromLiveInfo(snapshot);
|
||||
}
|
||||
|
||||
Future<KryzAudioHandler> _requireHandler() async {
|
||||
await initializeBackgroundAudio();
|
||||
final handler = _audioHandler;
|
||||
if (handler is! KryzAudioHandler) {
|
||||
throw StateError('KryzAudioHandler is not initialized');
|
||||
}
|
||||
_attachHandler(handler);
|
||||
return handler;
|
||||
}
|
||||
|
||||
void _attachHandler(AudioHandler handler) {
|
||||
if (_isAttached) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isAttached = true;
|
||||
_playbackStateSubscription = handler.playbackState.listen((state) {
|
||||
_setPlaybackStatus(_mapPlaybackStateToStatus(state));
|
||||
});
|
||||
_mediaItemSubscription = handler.mediaItem.listen((item) {
|
||||
if (item == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final title = item.title.trim().isEmpty ? 'KRYZ Live Stream' : item.title;
|
||||
final subtitle =
|
||||
(item.artist ?? '').trim().isEmpty ? 'KRYZ Radio' : item.artist!.trim();
|
||||
|
||||
if (title == _currentTitle && subtitle == _currentSubtitle) {
|
||||
return;
|
||||
}
|
||||
|
||||
_currentTitle = title;
|
||||
_currentSubtitle = subtitle;
|
||||
notifyListeners();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_playerStateSubscription.cancel();
|
||||
_player.dispose();
|
||||
_isDisposed = true;
|
||||
_playbackStateSubscription?.cancel();
|
||||
_mediaItemSubscription?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user