import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:just_audio/just_audio.dart'; import '../models/song.dart'; class PlayerService { static final PlayerService _instanz = PlayerService._(); factory PlayerService() => _instanz; PlayerService._(); AudioPlayer? _player; final List _warteschlange = []; int _aktuellerIndex = -1; StreamSubscription? _autoNextSub; AudioPlayer get _p { if (_player == null) { _player = AudioPlayer(); _autoNextSub = _player!.playerStateStream.listen((state) { if (state.processingState == ProcessingState.completed) { naechstes(); } }); } return _player!; } Song? get aktuellerSong => _aktuellerIndex >= 0 && _aktuellerIndex < _warteschlange.length ? _warteschlange[_aktuellerIndex] : null; bool get spieltAb => _player?.playing ?? false; Duration get position => _player?.position ?? Duration.zero; Duration get dauer => _player?.duration ?? Duration.zero; Stream get positionStream => _p.positionStream; Stream get stateStream => _p.playerStateStream; final StreamController _songWechsel = StreamController.broadcast(); Stream get onSongWechsel => _songWechsel.stream; Future spiele(Song song, {int position = 0}) async { _aktuellerIndex = _warteschlange.indexWhere((s) => s.id == song.id); if (_aktuellerIndex < 0) { _warteschlange.add(song); _aktuellerIndex = _warteschlange.length - 1; } try { await _p.setFilePath(song.dateiPfad); if (position > 0) await _p.seek(Duration(seconds: position)); await _p.play(); _songWechsel.add(song); } catch (e) { debugPrint('Fehler beim Abspielen: $e'); } } Future playPause() async { if (_player == null) return; if (_p.playing) { await _p.pause(); } else if (aktuellerSong != null) { await _p.play(); } } Future vorheriges() async { if (_player == null || aktuellerSong == null) return; final pos = _p.position; if (pos.inSeconds > 5) { await _p.seek(Duration.zero); } else { final neuerIndex = _aktuellerIndex - 1; if (neuerIndex >= 0) { await spiele(_warteschlange[neuerIndex]); } } } Future naechstes() async { final neuerIndex = _aktuellerIndex + 1; if (neuerIndex < _warteschlange.length) { await spiele(_warteschlange[neuerIndex]); } } void setWarteschlange(List songs, {int startIndex = 0}) { _warteschlange.clear(); _warteschlange.addAll(songs); _aktuellerIndex = startIndex; } void dispose() { _autoNextSub?.cancel(); _player?.dispose(); _songWechsel.close(); } }