播放逻辑修改

This commit is contained in:
rang 2025-12-08 23:46:43 +08:00
parent 420438c0df
commit 50a27fdf67
33 changed files with 788 additions and 761 deletions

View file

@ -1,8 +1,4 @@
import 'package:audio_service/audio_service.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:media_kit/media_kit.dart';
import 'package:vaani/features/player/providers/abs_provider.dart'
hide AbsAudioPlayer;
import 'package:vaani/shared/audio_player.dart';
class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
@ -39,11 +35,11 @@ class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
playing: playerState.playing,
// playing processingState
processingState: const {
ProcessingState.idle: AudioProcessingState.idle,
ProcessingState.loading: AudioProcessingState.loading,
ProcessingState.buffering: AudioProcessingState.buffering,
ProcessingState.ready: AudioProcessingState.ready,
ProcessingState.completed: AudioProcessingState.completed,
AbsProcessingState.idle: AudioProcessingState.idle,
AbsProcessingState.loading: AudioProcessingState.loading,
AbsProcessingState.buffering: AudioProcessingState.buffering,
AbsProcessingState.ready: AudioProcessingState.ready,
AbsProcessingState.completed: AudioProcessingState.completed,
}[playerState.processingState] ??
AudioProcessingState.idle,
),

View file

@ -1,33 +1,33 @@
// ignore_for_file: public_member_api_docs, sort_constructors_first
// import 'package:just_audio/just_audio.dart';
import 'package:shelfsdk/audiobookshelf_api.dart' as api;
// // ignore_for_file: public_member_api_docs, sort_constructors_first
// // import 'package:just_audio/just_audio.dart';
// import 'package:shelfsdk/audiobookshelf_api.dart' as api;
class AbsPlayerState {
api.BookExpanded? book;
//
final api.BookChapter? currentChapter;
//
final int currentIndex;
final bool playing;
// class AbsPlayerState {
// api.BookExpanded? book;
// //
// final api.BookChapter? currentChapter;
// //
// final int currentIndex;
// final bool playing;
AbsPlayerState({
this.book,
this.currentChapter,
this.currentIndex = 0,
this.playing = false,
});
// AbsPlayerState({
// this.book,
// this.currentChapter,
// this.currentIndex = 0,
// this.playing = false,
// });
AbsPlayerState copyWith({
api.BookExpanded? book,
api.BookChapter? currentChapter,
int? currentIndex,
bool? playing,
}) {
return AbsPlayerState(
book: book ?? this.book,
currentChapter: currentChapter ?? this.currentChapter,
currentIndex: currentIndex ?? this.currentIndex,
playing: playing ?? this.playing,
);
}
}
// AbsPlayerState copyWith({
// api.BookExpanded? book,
// api.BookChapter? currentChapter,
// int? currentIndex,
// bool? playing,
// }) {
// return AbsPlayerState(
// book: book ?? this.book,
// currentChapter: currentChapter ?? this.currentChapter,
// currentIndex: currentIndex ?? this.currentIndex,
// playing: playing ?? this.playing,
// );
// }
// }

View file

@ -1,468 +1,468 @@
// my_audio_handler.dart
import 'dart:io';
// // my_audio_handler.dart
// import 'dart:io';
import 'package:audio_service/audio_service.dart';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:just_audio/just_audio.dart';
import 'package:logging/logging.dart';
import 'package:rxdart/rxdart.dart';
import 'package:shelfsdk/audiobookshelf_api.dart' hide NotificationSettings;
import 'package:vaani/features/player/core/player_status.dart' as core;
import 'package:vaani/features/player/providers/player_status_provider.dart';
import 'package:vaani/features/settings/app_settings_provider.dart';
import 'package:vaani/features/settings/models/app_settings.dart';
import 'package:vaani/shared/extensions/chapter.dart';
import 'package:vaani/shared/extensions/model_conversions.dart';
// import 'package:audio_service/audio_service.dart';
// import 'package:collection/collection.dart';
// import 'package:flutter/foundation.dart';
// import 'package:hooks_riverpod/hooks_riverpod.dart';
// import 'package:just_audio/just_audio.dart';
// import 'package:logging/logging.dart';
// import 'package:rxdart/rxdart.dart';
// import 'package:shelfsdk/audiobookshelf_api.dart' hide NotificationSettings;
// import 'package:vaani/features/player/core/player_status.dart' as core;
// import 'package:vaani/features/player/providers/player_status_provider.dart';
// import 'package:vaani/features/settings/app_settings_provider.dart';
// import 'package:vaani/features/settings/models/app_settings.dart';
// import 'package:vaani/shared/extensions/chapter.dart';
// import 'package:vaani/shared/extensions/model_conversions.dart';
// add a small offset so the display does not show the previous chapter for a split second
final offset = Duration(milliseconds: 10);
// // add a small offset so the display does not show the previous chapter for a split second
// final offset = Duration(milliseconds: 10);
final _logger = Logger('AudiobookPlayer');
// final _logger = Logger('AudiobookPlayer');
class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
final AudioPlayer _player = AudioPlayer();
final Ref ref;
// class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
// final AudioPlayer _player = AudioPlayer();
// final Ref ref;
BookExpanded? _book;
BookExpanded? get book => _book;
// BookExpanded? _book;
// BookExpanded? get book => _book;
late NotificationSettings notificationSettings;
// late NotificationSettings notificationSettings;
final _currentChapterObject = BehaviorSubject<BookChapter?>.seeded(null);
AbsAudioHandler(this.ref) {
notificationSettings = ref.read(appSettingsProvider).notificationSettings;
ref.listen(appSettingsProvider, (a, b) {
if (a?.notificationSettings != b.notificationSettings) {
notificationSettings = b.notificationSettings;
}
});
final statusNotifier = ref.read(playerStatusProvider.notifier);
// final _currentChapterObject = BehaviorSubject<BookChapter?>.seeded(null);
// AbsAudioHandler(this.ref) {
// notificationSettings = ref.read(appSettingsProvider).notificationSettings;
// ref.listen(appSettingsProvider, (a, b) {
// if (a?.notificationSettings != b.notificationSettings) {
// notificationSettings = b.notificationSettings;
// }
// });
// final statusNotifier = ref.read(playerStatusProvider.notifier);
//
_player.playbackEventStream.map(_transformEvent).pipe(playbackState);
_player.playerStateStream.listen((event) {
if (event.playing) {
statusNotifier.setPlayStatusVerify(core.PlayStatus.playing);
} else {
statusNotifier.setPlayStatusVerify(core.PlayStatus.paused);
}
});
_player.positionStream.distinct().listen((position) {
final chapter = _book?.findChapterAtTime(positionInBook);
if (chapter != currentChapter) {
if (mediaItem.hasValue && chapter != null) {
// updateMediaItem(
// mediaItem.value!.copyWith(
// duration: chapter.duration,
// displayTitle: chapter.title,
// ),
// );
}
_currentChapterObject.sink.add(chapter);
}
});
}
// //
// _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
// _player.playerStateStream.listen((event) {
// if (event.playing) {
// statusNotifier.setPlayStatusVerify(core.PlayStatus.playing);
// } else {
// statusNotifier.setPlayStatusVerify(core.PlayStatus.paused);
// }
// });
// _player.positionStream.distinct().listen((position) {
// final chapter = _book?.findChapterAtTime(positionInBook);
// if (chapter != currentChapter) {
// if (mediaItem.hasValue && chapter != null) {
// // updateMediaItem(
// // mediaItem.value!.copyWith(
// // duration: chapter.duration,
// // displayTitle: chapter.title,
// // ),
// // );
// }
// _currentChapterObject.sink.add(chapter);
// }
// });
// }
//
Future<void> setSourceAudiobook(
BookExpanded book, {
bool preload = true,
required Uri baseUrl,
required String token,
Duration? initialPosition,
List<Uri>? downloadedUris,
required double volume,
required double speed,
}) async {
final appSettings = loadOrCreateAppSettings();
// if (book == null) {
// _book = null;
// _logger.info('Book is null, stopping player');
// return stop();
// }
if (_book == book) {
_logger.info('Book is the same, doing nothing');
return;
}
_book = book;
// //
// Future<void> setSourceAudiobook(
// BookExpanded book, {
// bool preload = true,
// required Uri baseUrl,
// required String token,
// Duration? initialPosition,
// List<Uri>? downloadedUris,
// required double volume,
// required double speed,
// }) async {
// final appSettings = loadOrCreateAppSettings();
// // if (book == null) {
// // _book = null;
// // _logger.info('Book is null, stopping player');
// // return stop();
// // }
// if (_book == book) {
// _logger.info('Book is the same, doing nothing');
// return;
// }
// _book = book;
final trackToPlay = book.findTrackAtTime(initialPosition ?? Duration.zero);
final trackToChapter =
book.findChapterAtTime(initialPosition ?? Duration.zero);
final initialIndex = book.tracks.indexOf(trackToPlay);
final initialPositionInTrack = initialPosition != null
? initialPosition - trackToPlay.startOffset
: null;
final title = appSettings.notificationSettings.primaryTitle
.formatNotificationTitle(book);
final album = appSettings.notificationSettings.secondaryTitle
.formatNotificationTitle(book);
// final trackToPlay = book.findTrackAtTime(initialPosition ?? Duration.zero);
// final trackToChapter =
// book.findChapterAtTime(initialPosition ?? Duration.zero);
// final initialIndex = book.tracks.indexOf(trackToPlay);
// final initialPositionInTrack = initialPosition != null
// ? initialPosition - trackToPlay.startOffset
// : null;
// final title = appSettings.notificationSettings.primaryTitle
// .formatNotificationTitle(book);
// final album = appSettings.notificationSettings.secondaryTitle
// .formatNotificationTitle(book);
//
List<AudioSource> audioSources = book.tracks
.map(
(track) => AudioSource.uri(
_getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
),
)
.toList();
// //
// List<AudioSource> audioSources = book.tracks
// .map(
// (track) => AudioSource.uri(
// _getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
// ),
// )
// .toList();
final item = MediaItem(
id: book.libraryItemId,
title: title,
album: album,
displayTitle: title,
displaySubtitle: album,
duration: trackToChapter.duration,
artUri: Uri.parse(
'$baseUrl/api/items/${book.libraryItemId}/cover?token=$token',
),
);
mediaItem.add(item);
await _player
.setAudioSources(
audioSources,
preload: preload,
initialIndex: initialIndex,
initialPosition: initialPositionInTrack,
)
.catchError((error) {
_logger.shout('Error in setting audio source: $error');
return null;
});
await player.seek(initialPositionInTrack, index: initialIndex);
// _player.seek(initialPositionInTrack, index: initialIndex);
setVolume(volume);
setSpeed(speed);
await play();
// final item = MediaItem(
// id: book.libraryItemId,
// title: title,
// album: album,
// displayTitle: title,
// displaySubtitle: album,
// duration: trackToChapter.duration,
// artUri: Uri.parse(
// '$baseUrl/api/items/${book.libraryItemId}/cover?token=$token',
// ),
// );
// mediaItem.add(item);
// await _player
// .setAudioSources(
// audioSources,
// preload: preload,
// initialIndex: initialIndex,
// initialPosition: initialPositionInTrack,
// )
// .catchError((error) {
// _logger.shout('Error in setting audio source: $error');
// return null;
// });
// await player.seek(initialPositionInTrack, index: initialIndex);
// // _player.seek(initialPositionInTrack, index: initialIndex);
// setVolume(volume);
// setSpeed(speed);
// await play();
//
// if (initialPosition != null) {
// await seekInBook(initialPosition);
// }
}
// //
// // if (initialPosition != null) {
// // await seekInBook(initialPosition);
// // }
// }
// //
// void _onTrackChanged(int trackIndex) {
// if (_book == null) return;
// // //
// // void _onTrackChanged(int trackIndex) {
// // if (_book == null) return;
// //
// // print('切换到音轨: ${_book!.tracks[trackIndex].title}');
// }
// // //
// // // print('切换到音轨: ${_book!.tracks[trackIndex].title}');
// // }
//
Future<void> skipToChapter(int chapterId) async {
if (_book == null) return;
// //
// Future<void> skipToChapter(int chapterId) async {
// if (_book == null) return;
final chapter = _book!.chapters.firstWhere(
(ch) => ch.id == chapterId,
orElse: () => throw Exception('Chapter not found'),
);
await seekInBook(chapter.start + offset);
}
// final chapter = _book!.chapters.firstWhere(
// (ch) => ch.id == chapterId,
// orElse: () => throw Exception('Chapter not found'),
// );
// await seekInBook(chapter.start + offset);
// }
BookExpanded? get Book => _book;
// BookExpanded? get Book => _book;
//
AudioTrack? get currentTrack {
if (_book == null || _player.currentIndex == null) {
return null;
}
return _book!.tracks[_player.currentIndex!];
}
// //
// AudioTrack? get currentTrack {
// if (_book == null || _player.currentIndex == null) {
// return null;
// }
// return _book!.tracks[_player.currentIndex!];
// }
//
BookChapter? get currentChapter {
return _currentChapterObject.value;
}
// //
// BookChapter? get currentChapter {
// return _currentChapterObject.value;
// }
Duration get position => _player.position;
Duration get positionInChapter {
return _player.position +
(currentTrack?.startOffset ?? Duration.zero) -
(currentChapter?.start ?? Duration.zero);
}
// Duration get position => _player.position;
// Duration get positionInChapter {
// return _player.position +
// (currentTrack?.startOffset ?? Duration.zero) -
// (currentChapter?.start ?? Duration.zero);
// }
Duration get positionInBook {
return _player.position + (currentTrack?.startOffset ?? Duration.zero);
}
// Duration get positionInBook {
// return _player.position + (currentTrack?.startOffset ?? Duration.zero);
// }
Duration get bufferedPositionInBook {
return _player.bufferedPosition +
(currentTrack?.startOffset ?? Duration.zero);
}
// Duration get bufferedPositionInBook {
// return _player.bufferedPosition +
// (currentTrack?.startOffset ?? Duration.zero);
// }
Duration? get chapterDuration => currentChapter?.duration;
// Duration? get chapterDuration => currentChapter?.duration;
Stream<PlayerState> get playerStateStream => _player.playerStateStream;
// Stream<PlayerState> get playerStateStream => _player.playerStateStream;
Stream<Duration> get positionStream => _player.positionStream;
// Stream<Duration> get positionStream => _player.positionStream;
Stream<Duration> get positionStreamInBook {
return _player.positionStream.map((position) {
return position + (currentTrack?.startOffset ?? Duration.zero);
});
}
// Stream<Duration> get positionStreamInBook {
// return _player.positionStream.map((position) {
// return position + (currentTrack?.startOffset ?? Duration.zero);
// });
// }
Stream<Duration> get slowPositionStreamInBook {
final superPositionStream = _player.createPositionStream(
steps: 100,
minPeriod: const Duration(milliseconds: 500),
maxPeriod: const Duration(seconds: 1),
);
return superPositionStream.map((position) {
return position + (currentTrack?.startOffset ?? Duration.zero);
});
}
// Stream<Duration> get slowPositionStreamInBook {
// final superPositionStream = _player.createPositionStream(
// steps: 100,
// minPeriod: const Duration(milliseconds: 500),
// maxPeriod: const Duration(seconds: 1),
// );
// return superPositionStream.map((position) {
// return position + (currentTrack?.startOffset ?? Duration.zero);
// });
// }
Stream<Duration> get bufferedPositionStreamInBook {
return _player.bufferedPositionStream.map((position) {
return position + (currentTrack?.startOffset ?? Duration.zero);
});
}
// Stream<Duration> get bufferedPositionStreamInBook {
// return _player.bufferedPositionStream.map((position) {
// return position + (currentTrack?.startOffset ?? Duration.zero);
// });
// }
Stream<Duration> get positionStreamInChapter {
return _player.positionStream.distinct().map((position) {
return position +
(currentTrack?.startOffset ?? Duration.zero) -
(currentChapter?.start ?? Duration.zero);
});
}
// Stream<Duration> get positionStreamInChapter {
// return _player.positionStream.distinct().map((position) {
// return position +
// (currentTrack?.startOffset ?? Duration.zero) -
// (currentChapter?.start ?? Duration.zero);
// });
// }
Stream<BookChapter?> get chapterStream => _currentChapterObject.stream;
// Stream<BookChapter?> get chapterStream => _currentChapterObject.stream;
Future<void> togglePlayPause() async {
// check if book is set
if (_book == null) {
_logger.warning('No book is set, not toggling play/pause');
}
return switch (_player.playerState) {
PlayerState(playing: var isPlaying) => isPlaying ? pause() : play(),
};
}
// Future<void> togglePlayPause() async {
// // check if book is set
// if (_book == null) {
// _logger.warning('No book is set, not toggling play/pause');
// }
// return switch (_player.playerState) {
// PlayerState(playing: var isPlaying) => isPlaying ? pause() : play(),
// };
// }
//
@override
Future<void> play() async {
await _player.play();
}
// //
// @override
// Future<void> play() async {
// await _player.play();
// }
@override
Future<void> pause() async {
await _player.pause();
}
// @override
// Future<void> pause() async {
// await _player.pause();
// }
// /
@override
Future<void> skipToNext() async {
if (_book == null) {
// 退
return _player.seekToNext();
}
final chapter = currentChapter;
if (chapter == null) {
// 退
return _player.seekToNext();
}
final chapterIndex = _book!.chapters.indexOf(chapter);
if (chapterIndex < _book!.chapters.length - 1) {
//
final nextChapter = _book!.chapters[chapterIndex + 1];
await skipToChapter(nextChapter.id);
}
}
// // /
// @override
// Future<void> skipToNext() async {
// if (_book == null) {
// // 退
// return _player.seekToNext();
// }
// final chapter = currentChapter;
// if (chapter == null) {
// // 退
// return _player.seekToNext();
// }
// final chapterIndex = _book!.chapters.indexOf(chapter);
// if (chapterIndex < _book!.chapters.length - 1) {
// //
// final nextChapter = _book!.chapters[chapterIndex + 1];
// await skipToChapter(nextChapter.id);
// }
// }
@override
Future<void> skipToPrevious() async {
final chapter = currentChapter;
if (_book == null || chapter == null) {
return _player.seekToPrevious();
}
final currentIndex = _book!.chapters.indexOf(chapter);
if (currentIndex > 0) {
//
final prevChapter = _book!.chapters[currentIndex - 1];
await skipToChapter(prevChapter.id);
} else {
//
await seekInBook(Duration.zero);
}
}
// @override
// Future<void> skipToPrevious() async {
// final chapter = currentChapter;
// if (_book == null || chapter == null) {
// return _player.seekToPrevious();
// }
// final currentIndex = _book!.chapters.indexOf(chapter);
// if (currentIndex > 0) {
// //
// final prevChapter = _book!.chapters[currentIndex - 1];
// await skipToChapter(prevChapter.id);
// } else {
// //
// await seekInBook(Duration.zero);
// }
// }
@override
Future<void> seek(Duration position) async {
// position 使
//
final track = currentTrack;
Duration startOffset = Duration.zero;
if (track != null) {
startOffset = track.startOffset;
}
await seekInBook(startOffset + position);
}
// @override
// Future<void> seek(Duration position) async {
// // position 使
// //
// final track = currentTrack;
// Duration startOffset = Duration.zero;
// if (track != null) {
// startOffset = track.startOffset;
// }
// await seekInBook(startOffset + position);
// }
Future<void> setVolume(double volume) async {
await _player.setVolume(volume);
}
// Future<void> setVolume(double volume) async {
// await _player.setVolume(volume);
// }
@override
Future<void> setSpeed(double speed) async {
await _player.setSpeed(speed);
}
// @override
// Future<void> setSpeed(double speed) async {
// await _player.setSpeed(speed);
// }
//
Future<void> seekInBook(Duration globalPosition) async {
if (_book == null) return;
//
final track = _book!.findTrackAtTime(globalPosition);
final index = _book!.tracks.indexOf(track);
Duration positionInTrack = globalPosition - track.startOffset;
if (positionInTrack < Duration.zero) {
positionInTrack = Duration.zero;
}
//
await _player.seek(positionInTrack, index: index);
}
// //
// Future<void> seekInBook(Duration globalPosition) async {
// if (_book == null) return;
// //
// final track = _book!.findTrackAtTime(globalPosition);
// final index = _book!.tracks.indexOf(track);
// Duration positionInTrack = globalPosition - track.startOffset;
// if (positionInTrack < Duration.zero) {
// positionInTrack = Duration.zero;
// }
// //
// await _player.seek(positionInTrack, index: index);
// }
AudioPlayer get player => _player;
PlaybackState _transformEvent(PlaybackEvent event) {
return PlaybackState(
controls: [
if ((kIsWeb || !Platform.isAndroid) &&
notificationSettings.mediaControls
.contains(NotificationMediaControl.skipToPreviousChapter))
MediaControl.skipToPrevious,
if (notificationSettings.mediaControls
.contains(NotificationMediaControl.rewind))
MediaControl.rewind,
if (_player.playing) MediaControl.pause else MediaControl.play,
if (notificationSettings.mediaControls
.contains(NotificationMediaControl.fastForward))
MediaControl.fastForward,
if ((kIsWeb || !Platform.isAndroid) &&
notificationSettings.mediaControls
.contains(NotificationMediaControl.skipToNextChapter))
MediaControl.skipToNext,
if (notificationSettings.mediaControls
.contains(NotificationMediaControl.stop))
MediaControl.stop,
],
systemActions: {
// if (kIsWeb || !Platform.isAndroid) MediaAction.skipToPrevious,
// MediaAction.rewind,
MediaAction.seek,
MediaAction.seekForward,
MediaAction.seekBackward,
// MediaAction.fastForward,
// MediaAction.stop,
// MediaAction.setSpeed,
// if (kIsWeb || !Platform.isAndroid) MediaAction.skipToNext,
},
androidCompactActionIndices: const [1, 2, 3],
processingState: const {
ProcessingState.idle: AudioProcessingState.idle,
ProcessingState.loading: AudioProcessingState.loading,
ProcessingState.buffering: AudioProcessingState.buffering,
ProcessingState.ready: AudioProcessingState.ready,
ProcessingState.completed: AudioProcessingState.completed,
}[_player.processingState] ??
AudioProcessingState.idle,
playing: _player.playing,
updatePosition: positionInChapter,
bufferedPosition: _player.bufferedPosition,
speed: _player.speed,
queueIndex: event.currentIndex,
captioningEnabled: false,
);
}
}
// AudioPlayer get player => _player;
// PlaybackState _transformEvent(PlaybackEvent event) {
// return PlaybackState(
// controls: [
// if ((kIsWeb || !Platform.isAndroid) &&
// notificationSettings.mediaControls
// .contains(NotificationMediaControl.skipToPreviousChapter))
// MediaControl.skipToPrevious,
// if (notificationSettings.mediaControls
// .contains(NotificationMediaControl.rewind))
// MediaControl.rewind,
// if (_player.playing) MediaControl.pause else MediaControl.play,
// if (notificationSettings.mediaControls
// .contains(NotificationMediaControl.fastForward))
// MediaControl.fastForward,
// if ((kIsWeb || !Platform.isAndroid) &&
// notificationSettings.mediaControls
// .contains(NotificationMediaControl.skipToNextChapter))
// MediaControl.skipToNext,
// if (notificationSettings.mediaControls
// .contains(NotificationMediaControl.stop))
// MediaControl.stop,
// ],
// systemActions: {
// // if (kIsWeb || !Platform.isAndroid) MediaAction.skipToPrevious,
// // MediaAction.rewind,
// MediaAction.seek,
// MediaAction.seekForward,
// MediaAction.seekBackward,
// // MediaAction.fastForward,
// // MediaAction.stop,
// // MediaAction.setSpeed,
// // if (kIsWeb || !Platform.isAndroid) MediaAction.skipToNext,
// },
// androidCompactActionIndices: const [1, 2, 3],
// processingState: const {
// ProcessingState.idle: AudioProcessingState.idle,
// ProcessingState.loading: AudioProcessingState.loading,
// ProcessingState.buffering: AudioProcessingState.buffering,
// ProcessingState.ready: AudioProcessingState.ready,
// ProcessingState.completed: AudioProcessingState.completed,
// }[_player.processingState] ??
// AudioProcessingState.idle,
// playing: _player.playing,
// updatePosition: positionInChapter,
// bufferedPosition: _player.bufferedPosition,
// speed: _player.speed,
// queueIndex: event.currentIndex,
// captioningEnabled: false,
// );
// }
// }
Uri _getUri(
AudioTrack track,
List<Uri>? downloadedUris, {
required Uri baseUrl,
required String token,
}) {
// check if the track is in the downloadedUris
final uri = downloadedUris?.firstWhereOrNull(
(element) {
return element.pathSegments.last == track.metadata?.filename;
},
);
// Uri _getUri(
// AudioTrack track,
// List<Uri>? downloadedUris, {
// required Uri baseUrl,
// required String token,
// }) {
// // check if the track is in the downloadedUris
// final uri = downloadedUris?.firstWhereOrNull(
// (element) {
// return element.pathSegments.last == track.metadata?.filename;
// },
// );
return uri ??
Uri.parse('${baseUrl.toString()}${track.contentUrl}?token=$token');
}
// return uri ??
// Uri.parse('${baseUrl.toString()}${track.contentUrl}?token=$token');
// }
extension FormatNotificationTitle on String {
String formatNotificationTitle(BookExpanded book) {
return replaceAllMapped(
RegExp(r'\$(\w+)'),
(match) {
final type = match.group(1);
return NotificationTitleType.values
.firstWhere((element) => element.name == type)
.extractFrom(book) ??
match.group(0) ??
'';
},
);
}
}
// extension FormatNotificationTitle on String {
// String formatNotificationTitle(BookExpanded book) {
// return replaceAllMapped(
// RegExp(r'\$(\w+)'),
// (match) {
// final type = match.group(1);
// return NotificationTitleType.values
// .firstWhere((element) => element.name == type)
// .extractFrom(book) ??
// match.group(0) ??
// '';
// },
// );
// }
// }
extension NotificationTitleUtils on NotificationTitleType {
String? extractFrom(BookExpanded book) {
var bookMetadataExpanded = book.metadata.asBookMetadataExpanded;
switch (this) {
case NotificationTitleType.bookTitle:
return bookMetadataExpanded.title;
case NotificationTitleType.chapterTitle:
// TODO: implement chapter title; depends on https://github.com/Dr-Blank/Vaani/issues/2
return bookMetadataExpanded.title;
case NotificationTitleType.author:
return bookMetadataExpanded.authorName;
case NotificationTitleType.narrator:
return bookMetadataExpanded.narratorName;
case NotificationTitleType.series:
return bookMetadataExpanded.seriesName;
case NotificationTitleType.subtitle:
return bookMetadataExpanded.subtitle;
case NotificationTitleType.year:
return bookMetadataExpanded.publishedYear;
}
}
}
// extension NotificationTitleUtils on NotificationTitleType {
// String? extractFrom(BookExpanded book) {
// var bookMetadataExpanded = book.metadata.asBookMetadataExpanded;
// switch (this) {
// case NotificationTitleType.bookTitle:
// return bookMetadataExpanded.title;
// case NotificationTitleType.chapterTitle:
// // TODO: implement chapter title; depends on https://github.com/Dr-Blank/Vaani/issues/2
// return bookMetadataExpanded.title;
// case NotificationTitleType.author:
// return bookMetadataExpanded.authorName;
// case NotificationTitleType.narrator:
// return bookMetadataExpanded.narratorName;
// case NotificationTitleType.series:
// return bookMetadataExpanded.seriesName;
// case NotificationTitleType.subtitle:
// return bookMetadataExpanded.subtitle;
// case NotificationTitleType.year:
// return bookMetadataExpanded.publishedYear;
// }
// }
// }
extension BookExpandedExtension on BookExpanded {
BookChapter findChapterAtTime(Duration position) {
return chapters.firstWhere(
(element) {
return element.start <= position && element.end >= position + offset;
},
orElse: () => chapters.first,
);
}
// extension BookExpandedExtension on BookExpanded {
// BookChapter findChapterAtTime(Duration position) {
// return chapters.firstWhere(
// (element) {
// return element.start <= position && element.end >= position + offset;
// },
// orElse: () => chapters.first,
// );
// }
AudioTrack findTrackAtTime(Duration position) {
return tracks.firstWhere(
(element) {
return element.startOffset <= position &&
element.startOffset + element.duration >= position + offset;
},
orElse: () => tracks.first,
);
}
// AudioTrack findTrackAtTime(Duration position) {
// return tracks.firstWhere(
// (element) {
// return element.startOffset <= position &&
// element.startOffset + element.duration >= position + offset;
// },
// orElse: () => tracks.first,
// );
// }
int findTrackIndexAtTime(Duration position) {
return tracks.indexWhere((element) {
return element.startOffset <= position &&
element.startOffset + element.duration >= position + offset;
});
}
// int findTrackIndexAtTime(Duration position) {
// return tracks.indexWhere((element) {
// return element.startOffset <= position &&
// element.startOffset + element.duration >= position + offset;
// });
// }
Duration getTrackStartOffset(int index) {
return tracks[index].startOffset;
}
}
// Duration getTrackStartOffset(int index) {
// return tracks[index].startOffset;
// }
// }