mirror of
https://github.com/Dr-Blank/Vaani.git
synced 2026-02-16 06:19:35 +00:00
更改播放音频方式
This commit is contained in:
parent
4a02b757bc
commit
eb1955e5e6
25 changed files with 2102 additions and 1250 deletions
|
|
@ -12,17 +12,14 @@ import 'package:vaani/features/downloads/providers/download_manager.dart'
|
|||
downloadManagerProvider,
|
||||
isItemDownloadedProvider,
|
||||
isItemDownloadingProvider,
|
||||
itemDownloadProgressProvider,
|
||||
simpleDownloadManagerProvider;
|
||||
itemDownloadProgressProvider;
|
||||
import 'package:vaani/features/item_viewer/view/library_item_page.dart';
|
||||
import 'package:vaani/features/per_book_settings/providers/book_settings_provider.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
import 'package:vaani/features/player/providers/player_form.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/generated/l10n.dart';
|
||||
import 'package:vaani/globals.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
import 'package:vaani/settings/api_settings_provider.dart';
|
||||
import 'package:vaani/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/shared/extensions/model_conversions.dart';
|
||||
import 'package:vaani/shared/utils.dart';
|
||||
|
||||
|
|
@ -302,7 +299,7 @@ class AlreadyItemDownloadedButton extends HookConsumerWidget {
|
|||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isBookPlaying = ref.watch(audiobookPlayerProvider).book != null;
|
||||
final isBookPlaying = ref.watch(playStateProvider).playing;
|
||||
|
||||
return IconButton(
|
||||
onPressed: () {
|
||||
|
|
@ -435,9 +432,14 @@ class _LibraryItemPlayButton extends HookConsumerWidget {
|
|||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final book = item.media.asBookExpanded;
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
final isCurrentBookSetInPlayer = player.book == book;
|
||||
final isPlayingThisBook = player.playing && isCurrentBookSetInPlayer;
|
||||
final session = ref.watch(sessionProvider.select((v) => v.session));
|
||||
final sessionLoading =
|
||||
ref.watch(sessionLoadingProvider(book.libraryItemId));
|
||||
final playerState = ref.watch(playStateProvider);
|
||||
// final player = ref.watch(audiobookPlayerProvider);
|
||||
final isCurrentBookSetInPlayer =
|
||||
session?.libraryItemId == book.libraryItemId;
|
||||
final isPlayingThisBook = playerState.playing && isCurrentBookSetInPlayer;
|
||||
|
||||
final userMediaProgress = item.userMediaProgress;
|
||||
final isBookCompleted = userMediaProgress?.isFinished ?? false;
|
||||
|
|
@ -464,14 +466,13 @@ class _LibraryItemPlayButton extends HookConsumerWidget {
|
|||
}
|
||||
|
||||
return ElevatedButton.icon(
|
||||
onPressed: () => libraryItemPlayButtonOnPressed(
|
||||
ref: ref,
|
||||
book: book,
|
||||
userMediaProgress: userMediaProgress,
|
||||
),
|
||||
onPressed: () => session?.libraryItemId == book.libraryItemId
|
||||
? ref.read(sessionProvider).load(book.libraryItemId, null)
|
||||
: ref.read(playerProvider).togglePlayPause(),
|
||||
icon: Hero(
|
||||
tag: HeroTagPrefixes.libraryItemPlayButton + book.libraryItemId,
|
||||
child: DynamicItemPlayIcon(
|
||||
isLoading: sessionLoading,
|
||||
isCurrentBookSetInPlayer: isCurrentBookSetInPlayer,
|
||||
isPlayingThisBook: isPlayingThisBook,
|
||||
isBookCompleted: isBookCompleted,
|
||||
|
|
@ -493,87 +494,32 @@ class DynamicItemPlayIcon extends StatelessWidget {
|
|||
required this.isCurrentBookSetInPlayer,
|
||||
required this.isPlayingThisBook,
|
||||
required this.isBookCompleted,
|
||||
this.isLoading = false,
|
||||
});
|
||||
|
||||
final bool isCurrentBookSetInPlayer;
|
||||
final bool isPlayingThisBook;
|
||||
final bool isBookCompleted;
|
||||
final bool isLoading;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Icon(
|
||||
isCurrentBookSetInPlayer
|
||||
? isPlayingThisBook
|
||||
? Icons.pause_rounded
|
||||
: Icons.play_arrow_rounded
|
||||
: isBookCompleted
|
||||
? Icons.replay_rounded
|
||||
: Icons.play_arrow_rounded,
|
||||
);
|
||||
return isLoading
|
||||
? SizedBox(
|
||||
// width: 20,
|
||||
// height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 4,
|
||||
),
|
||||
)
|
||||
: Icon(
|
||||
isCurrentBookSetInPlayer
|
||||
? isPlayingThisBook
|
||||
? Icons.pause_rounded
|
||||
: Icons.play_arrow_rounded
|
||||
: isBookCompleted
|
||||
? Icons.replay_rounded
|
||||
: Icons.play_arrow_rounded,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles the play button pressed on the library item
|
||||
Future<void> libraryItemPlayButtonOnPressed({
|
||||
required WidgetRef ref,
|
||||
required shelfsdk.BookExpanded book,
|
||||
shelfsdk.MediaProgress? userMediaProgress,
|
||||
}) async {
|
||||
appLogger.info('Pressed play/resume button');
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
// final bookSettings = ref.watch(bookSettingsProvider(book.libraryItemId));
|
||||
|
||||
final isCurrentBookSetInPlayer = player.book == book;
|
||||
final isPlayingThisBook = player.playing && isCurrentBookSetInPlayer;
|
||||
|
||||
Future<void>? setSourceFuture;
|
||||
// set the book to the player if not already set
|
||||
if (!isCurrentBookSetInPlayer) {
|
||||
appLogger.info('Setting the book ${book.libraryItemId}');
|
||||
appLogger.info('Initial position: ${userMediaProgress?.currentTime}');
|
||||
final downloadManager = ref.watch(simpleDownloadManagerProvider);
|
||||
final libItem =
|
||||
await ref.read(libraryItemProvider(book.libraryItemId).future);
|
||||
final downloadedUris = await downloadManager.getDownloadedFilesUri(libItem);
|
||||
setSourceFuture = player.setSourceAudiobook(
|
||||
book,
|
||||
initialPosition: userMediaProgress?.currentTime,
|
||||
downloadedUris: downloadedUris,
|
||||
);
|
||||
} else {
|
||||
appLogger.info('Book was already set');
|
||||
if (isPlayingThisBook) {
|
||||
appLogger.info('Pausing the book');
|
||||
await player.pause();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// set the volume as this is the first time playing and dismissing causes the volume to go to 0
|
||||
var bookPlayerSettings =
|
||||
ref.read(bookSettingsProvider(book.libraryItemId)).playerSettings;
|
||||
var appPlayerSettings = ref.read(appSettingsProvider).playerSettings;
|
||||
|
||||
var configurePlayerForEveryBook =
|
||||
appPlayerSettings.configurePlayerForEveryBook;
|
||||
|
||||
await Future.wait([
|
||||
setSourceFuture ?? Future.value(),
|
||||
// set the volume
|
||||
player.setVolume(
|
||||
configurePlayerForEveryBook
|
||||
? bookPlayerSettings.preferredDefaultVolume ??
|
||||
appPlayerSettings.preferredDefaultVolume
|
||||
: appPlayerSettings.preferredDefaultVolume,
|
||||
),
|
||||
// set the speed
|
||||
player.setSpeed(
|
||||
configurePlayerForEveryBook
|
||||
? bookPlayerSettings.preferredDefaultSpeed ??
|
||||
appPlayerSettings.preferredDefaultSpeed
|
||||
: appPlayerSettings.preferredDefaultSpeed,
|
||||
),
|
||||
]);
|
||||
|
||||
// toggle play/pause
|
||||
await player.play();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,277 @@
|
|||
import 'dart:async';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/features/player/core/audiobook_player.dart';
|
||||
import 'package:vaani/shared/extensions/obfuscation.dart';
|
||||
|
||||
final _logger = Logger('PlaybackReporter');
|
||||
|
||||
/// this playback reporter will watch the player and report to the server
|
||||
///
|
||||
/// it will by default report every 10 seconds
|
||||
/// and also report when the player is paused/stopped/finished/playing
|
||||
class PlaybackReporter {
|
||||
/// The player to watch
|
||||
final AudiobookPlayer player;
|
||||
|
||||
/// the api to report to
|
||||
final AudiobookshelfApi authenticatedApi;
|
||||
|
||||
/// The stopwatch to keep track of the time since the last report
|
||||
///
|
||||
/// this should only run when media is playing
|
||||
final _stopwatch = Stopwatch();
|
||||
|
||||
/// subscriptions to listen and then cancel when disposing
|
||||
final List<StreamSubscription> _subscriptions = [];
|
||||
|
||||
Duration _reportingInterval;
|
||||
|
||||
/// the duration to wait before reporting
|
||||
Duration get reportingInterval => _reportingInterval;
|
||||
set reportingInterval(Duration value) {
|
||||
_reportingInterval = value;
|
||||
_cancelReportTimer();
|
||||
_setReportTimerIfNotAlready();
|
||||
_logger.info('set interval: $value');
|
||||
}
|
||||
|
||||
/// the minimum duration to report
|
||||
final Duration reportingDurationThreshold;
|
||||
|
||||
/// the duration to wait before starting the reporting
|
||||
/// this is to ignore the initial duration in case user is browsing
|
||||
final Duration? minimumPositionForReporting;
|
||||
|
||||
/// the duration to mark the book as complete when the time left is less than this
|
||||
final Duration markCompleteWhenTimeLeft;
|
||||
|
||||
/// timer to report every 10 seconds
|
||||
/// tracking the time since the last report
|
||||
Timer? _reportTimer;
|
||||
|
||||
PlaybackReporter(
|
||||
this.player,
|
||||
this.authenticatedApi, {
|
||||
required PlaybackSession session,
|
||||
this.reportingDurationThreshold = const Duration(seconds: 1),
|
||||
Duration reportingInterval = const Duration(seconds: 10),
|
||||
this.minimumPositionForReporting,
|
||||
this.markCompleteWhenTimeLeft = const Duration(seconds: 5),
|
||||
}) : _reportingInterval = reportingInterval,
|
||||
_session = session {
|
||||
// initial conditions
|
||||
if (player.playing) {
|
||||
_stopwatch.start();
|
||||
_setReportTimerIfNotAlready();
|
||||
_logger.fine('starting stopwatch');
|
||||
} else {
|
||||
_logger.fine('not starting stopwatch');
|
||||
}
|
||||
|
||||
_subscriptions.add(
|
||||
player.playerStateStream.listen((state) async {
|
||||
// set timer if any book is playing and cancel if not
|
||||
if (player.book != null) {
|
||||
if (state.playing) {
|
||||
_setReportTimerIfNotAlready();
|
||||
} else {
|
||||
_cancelReportTimer();
|
||||
}
|
||||
} else if (player.book == null && _reportTimer != null) {
|
||||
_logger.info('book is null, closing session');
|
||||
await closeSession();
|
||||
_cancelReportTimer();
|
||||
}
|
||||
|
||||
// start or stop the stopwatch based on the playing state
|
||||
if (state.playing) {
|
||||
_stopwatch.start();
|
||||
_logger.fine(
|
||||
'player state observed, starting stopwatch at ${_stopwatch.elapsed}',
|
||||
);
|
||||
} else if (!state.playing) {
|
||||
_stopwatch.stop();
|
||||
_logger.fine(
|
||||
'player state observed, stopping stopwatch at ${_stopwatch.elapsed}',
|
||||
);
|
||||
await tryReportPlayback(null);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
_logger.fine(
|
||||
'initialized with reportingInterval: $reportingInterval, reportingDurationThreshold: $reportingDurationThreshold',
|
||||
);
|
||||
_logger.fine(
|
||||
'initialized with minimumPositionForReporting: $minimumPositionForReporting, markCompleteWhenTimeLeft: $markCompleteWhenTimeLeft',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> tryReportPlayback(_) async {
|
||||
_logger.fine(
|
||||
'callback called when elapsed ${_stopwatch.elapsed}',
|
||||
);
|
||||
if (player.book != null &&
|
||||
player.positionInBook >=
|
||||
player.book!.duration - markCompleteWhenTimeLeft) {
|
||||
_logger.info(
|
||||
'marking complete as time left is less than $markCompleteWhenTimeLeft',
|
||||
);
|
||||
await markComplete();
|
||||
return;
|
||||
}
|
||||
if (_stopwatch.elapsed > reportingDurationThreshold) {
|
||||
_logger.fine(
|
||||
'reporting now with elapsed ${_stopwatch.elapsed} > threshold $reportingDurationThreshold',
|
||||
);
|
||||
await syncCurrentPosition();
|
||||
}
|
||||
}
|
||||
|
||||
/// dispose the timer
|
||||
Future<void> dispose() async {
|
||||
for (var sub in _subscriptions) {
|
||||
sub.cancel();
|
||||
}
|
||||
await closeSession();
|
||||
_stopwatch.stop();
|
||||
_reportTimer?.cancel();
|
||||
|
||||
_logger.fine('disposed');
|
||||
}
|
||||
|
||||
/// current sessionId
|
||||
/// this is used to report the playback
|
||||
PlaybackSession? _session;
|
||||
String? get sessionId => _session?.id;
|
||||
|
||||
Future<void> markComplete() async {
|
||||
if (player.book == null) {
|
||||
throw NoAudiobookPlayingError();
|
||||
}
|
||||
await authenticatedApi.me.createUpdateMediaProgress(
|
||||
libraryItemId: player.book!.libraryItemId,
|
||||
parameters: CreateUpdateProgressReqParams(
|
||||
isFinished: true,
|
||||
currentTime: player.positionInBook,
|
||||
duration: player.book!.duration,
|
||||
),
|
||||
responseErrorHandler: _responseErrorHandler,
|
||||
);
|
||||
_logger.info('Marked complete for book: ${player.book!.libraryItemId}');
|
||||
}
|
||||
|
||||
Future<void> syncCurrentPosition() async {
|
||||
final data = _getSyncData();
|
||||
if (data == null) {
|
||||
await closeSession();
|
||||
}
|
||||
|
||||
final currentPosition = player.positionInBook;
|
||||
|
||||
await authenticatedApi.sessions.syncOpen(
|
||||
sessionId: sessionId!,
|
||||
parameters: _getSyncData()!,
|
||||
responseErrorHandler: _responseErrorHandler,
|
||||
);
|
||||
|
||||
_logger.fine(
|
||||
'Synced position: $currentPosition with timeListened: ${_stopwatch.elapsed} for session: $sessionId',
|
||||
);
|
||||
|
||||
// reset the stopwatch
|
||||
_stopwatch.reset();
|
||||
}
|
||||
|
||||
Future<void> closeSession() async {
|
||||
if (sessionId == null) {
|
||||
_logger.warning('No session to close');
|
||||
return;
|
||||
}
|
||||
|
||||
await authenticatedApi.sessions.closeOpen(
|
||||
sessionId: sessionId!,
|
||||
parameters: _getSyncData(),
|
||||
responseErrorHandler: _responseErrorHandler,
|
||||
);
|
||||
_session = null;
|
||||
_logger.info('Closed session');
|
||||
}
|
||||
|
||||
void _setReportTimerIfNotAlready() {
|
||||
if (_reportTimer != null) return;
|
||||
_reportTimer = Timer.periodic(_reportingInterval, tryReportPlayback);
|
||||
_logger.fine('set timer with interval: $_reportingInterval');
|
||||
}
|
||||
|
||||
void _cancelReportTimer() {
|
||||
_reportTimer?.cancel();
|
||||
_reportTimer = null;
|
||||
_logger.fine('cancelled timer');
|
||||
}
|
||||
|
||||
void _responseErrorHandler(http.Response response, [error]) {
|
||||
if (response.statusCode != 200) {
|
||||
_logger.severe('Error with api: ${response.obfuscate()}, $error');
|
||||
throw PlaybackSyncError(
|
||||
'Error syncing position: ${response.body}, $error',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
SyncSessionReqParams? _getSyncData() {
|
||||
if (player.book?.libraryItemId != _session?.libraryItemId) {
|
||||
_logger.info(
|
||||
'Book changed, not syncing position for session: $sessionId',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// if in the ignore duration, don't sync
|
||||
if (minimumPositionForReporting != null &&
|
||||
player.positionInBook < minimumPositionForReporting!) {
|
||||
// but if elapsed time is more than the minimumPositionForReporting, sync
|
||||
if (_stopwatch.elapsed > minimumPositionForReporting!) {
|
||||
_logger.info(
|
||||
'Syncing position despite being less than minimumPositionForReporting as elapsed time is more: ${_stopwatch.elapsed}',
|
||||
);
|
||||
} else {
|
||||
_logger.info(
|
||||
'Ignoring sync for position: ${player.positionInBook} < $minimumPositionForReporting',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return SyncSessionReqParams(
|
||||
currentTime: player.positionInBook,
|
||||
timeListened: _stopwatch.elapsed,
|
||||
duration: player.book?.duration ?? Duration.zero,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PlaybackSyncError implements Exception {
|
||||
String message;
|
||||
|
||||
PlaybackSyncError([this.message = 'Error syncing playback']);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'PlaybackSyncError: $message';
|
||||
}
|
||||
}
|
||||
|
||||
class NoAudiobookPlayingError implements Exception {
|
||||
String message;
|
||||
|
||||
NoAudiobookPlayingError([this.message = 'No audiobook is playing']);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'NoAudiobookPlayingError: $message';
|
||||
}
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ library;
|
|||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:just_audio_background/just_audio_background.dart';
|
||||
// import 'package:just_audio_background/just_audio_background.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
|
||||
|
|
@ -124,19 +124,19 @@ class AudiobookPlayer extends AudioPlayer {
|
|||
// );
|
||||
return AudioSource.uri(
|
||||
retrievedUri,
|
||||
tag: MediaItem(
|
||||
// Specify a unique ID for each media item:
|
||||
id: book.libraryItemId + track.index.toString(),
|
||||
// Metadata to display in the notification:
|
||||
title: appSettings.notificationSettings.primaryTitle
|
||||
.formatNotificationTitle(book),
|
||||
album: appSettings.notificationSettings.secondaryTitle
|
||||
.formatNotificationTitle(book),
|
||||
artUri: artworkUri ??
|
||||
Uri.parse(
|
||||
'$baseUrl/api/items/${book.libraryItemId}/cover?token=$token&width=800',
|
||||
),
|
||||
),
|
||||
// tag: MediaItem(
|
||||
// // Specify a unique ID for each media item:
|
||||
// id: book.libraryItemId + track.index.toString(),
|
||||
// // Metadata to display in the notification:
|
||||
// title: appSettings.notificationSettings.primaryTitle
|
||||
// .formatNotificationTitle(book),
|
||||
// album: appSettings.notificationSettings.secondaryTitle
|
||||
// .formatNotificationTitle(book),
|
||||
// artUri: artworkUri ??
|
||||
// Uri.parse(
|
||||
// '$baseUrl/api/items/${book.libraryItemId}/cover?token=$token&width=800',
|
||||
// ),
|
||||
// ),
|
||||
);
|
||||
}).toList();
|
||||
await setAudioSources(
|
||||
|
|
|
|||
|
|
@ -1,33 +1,30 @@
|
|||
// 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:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/shared/extensions/chapter.dart';
|
||||
|
||||
// add a small offset so the display does not show the previous chapter for a split second
|
||||
final offset = Duration(milliseconds: 10);
|
||||
|
||||
class HookAudioHandler extends BaseAudioHandler {
|
||||
class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
|
||||
final AudioPlayer _player = AudioPlayer();
|
||||
final List<AudioSource> _playlist = [];
|
||||
// final List<AudioSource> _playlist = [];
|
||||
final Ref ref;
|
||||
|
||||
BookExpanded? _book;
|
||||
PlaybackSessionExpanded? _session;
|
||||
|
||||
/// the authentication token to access the [AudioTrack.contentUrl]
|
||||
final String token;
|
||||
|
||||
/// the base url for the audio files
|
||||
final Uri baseUrl;
|
||||
|
||||
HookAudioHandler(this.ref, {required this.token, required this.baseUrl}) {
|
||||
AbsAudioHandler(this.ref) {
|
||||
_setupAudioPlayer();
|
||||
}
|
||||
|
||||
void _setupAudioPlayer() {
|
||||
_player.setAudioSources(_playlist);
|
||||
|
||||
// // 监听播放位置变化,更新全局位置
|
||||
// _player.positionStream.listen((position) {
|
||||
// // _updateGlobalPosition(position);
|
||||
|
|
@ -42,49 +39,58 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
|
||||
// 转发播放状态
|
||||
_player.playbackEventStream.map(_transformEvent).pipe(playbackState);
|
||||
_player.playerStateStream.distinct().listen((event) {
|
||||
ref.read(playStateProvider.notifier).setState(event);
|
||||
});
|
||||
}
|
||||
|
||||
// 加载有声书
|
||||
Future<void> setSourceAudiobook(
|
||||
BookExpanded audiobook, {
|
||||
Duration? initialPosition,
|
||||
PlaybackSessionExpanded playbackSession, {
|
||||
required Uri baseUrl,
|
||||
required String token,
|
||||
List<Uri>? downloadedUris,
|
||||
}) async {
|
||||
_book = audiobook;
|
||||
|
||||
// 清空现有播放列表
|
||||
_playlist.clear();
|
||||
_session = playbackSession;
|
||||
|
||||
// 添加所有音轨
|
||||
for (final track in audiobook.tracks) {
|
||||
final audioSource = ProgressiveAudioSource(
|
||||
_getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
|
||||
tag: MediaItem(
|
||||
id: '${audiobook.libraryItemId}${track.index}',
|
||||
title: track.title,
|
||||
duration: track.duration,
|
||||
List<AudioSource> audioSources = [];
|
||||
for (final track in playbackSession.audioTracks) {
|
||||
audioSources.add(
|
||||
AudioSource.uri(
|
||||
_getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
|
||||
),
|
||||
);
|
||||
_playlist.add(audioSource);
|
||||
}
|
||||
|
||||
// 初始化队列显示
|
||||
final mediaItems = audiobook.tracks
|
||||
.map(
|
||||
(track) => MediaItem(
|
||||
id: '${audiobook.libraryItemId}${track.index}',
|
||||
title: track.title,
|
||||
duration: track.duration,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
|
||||
queue.add(mediaItems);
|
||||
playMediaItem(
|
||||
MediaItem(
|
||||
id: playbackSession.libraryItemId,
|
||||
album: playbackSession.mediaMetadata.title,
|
||||
title: playbackSession.displayTitle,
|
||||
displaySubtitle: playbackSession.mediaType == MediaType.book
|
||||
? (playbackSession.mediaMetadata as BookMetadata).subtitle
|
||||
: null,
|
||||
duration: playbackSession.duration,
|
||||
artUri: Uri.parse(
|
||||
'$baseUrl/api/items/${playbackSession.libraryItemId}/cover?token=$token',
|
||||
),
|
||||
),
|
||||
);
|
||||
final track = playbackSession.findTrackAtTime(playbackSession.currentTime);
|
||||
final index = playbackSession.audioTracks.indexOf(track);
|
||||
|
||||
await _player.setAudioSources(
|
||||
audioSources,
|
||||
initialIndex: index,
|
||||
initialPosition: playbackSession.currentTime - track.startOffset,
|
||||
);
|
||||
_player.seek(playbackSession.currentTime - track.startOffset, index: index);
|
||||
await play();
|
||||
// 恢复上次播放位置(如果有)
|
||||
if (initialPosition != null) {
|
||||
await seekToPosition(initialPosition);
|
||||
}
|
||||
// if (initialPosition != null) {
|
||||
// await seekInBook(initialPosition);
|
||||
// }
|
||||
}
|
||||
|
||||
// // 音轨切换处理
|
||||
|
|
@ -97,19 +103,19 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
|
||||
// 核心功能:跳转到指定章节
|
||||
Future<void> skipToChapter(int chapterId) async {
|
||||
if (_book == null) return;
|
||||
if (_session == null) return;
|
||||
|
||||
final chapter = _book!.chapters.firstWhere(
|
||||
final chapter = _session!.chapters.firstWhere(
|
||||
(ch) => ch.id == chapterId,
|
||||
orElse: () => throw Exception('Chapter not found'),
|
||||
);
|
||||
|
||||
await seekToPosition(chapter.start + offset);
|
||||
await seekInBook(chapter.start + offset);
|
||||
}
|
||||
|
||||
Duration get positionInBook {
|
||||
if (_book != null && _player.currentIndex != null) {
|
||||
return _book!.tracks[_player.currentIndex!].startOffset +
|
||||
if (_session != null && _player.currentIndex != null) {
|
||||
return _session!.audioTracks[_player.currentIndex!].startOffset +
|
||||
_player.position;
|
||||
}
|
||||
return Duration.zero;
|
||||
|
|
@ -117,31 +123,61 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
|
||||
// 当前音轨
|
||||
AudioTrack? get currentTrack {
|
||||
if (_book == null) {
|
||||
if (_session == null) {
|
||||
return null;
|
||||
}
|
||||
return _book!.findTrackAtTime(positionInBook);
|
||||
return _session!.findTrackAtTime(positionInBook);
|
||||
}
|
||||
|
||||
// 当前章节
|
||||
BookChapter? get currentChapter {
|
||||
if (_book == null) {
|
||||
if (_session == null) {
|
||||
return null;
|
||||
}
|
||||
return _book!.findChapterAtTime(positionInBook);
|
||||
return _session!.findChapterAtTime(positionInBook);
|
||||
}
|
||||
|
||||
Duration? get chapterDuration => currentChapter?.duration;
|
||||
Stream<Duration> get positionStream => _player.positionStream;
|
||||
Stream<Duration> get positionStreamInChapter {
|
||||
return _player.positionStream.map((position) {
|
||||
final currentIndex = _player.currentIndex;
|
||||
if (_session == null || currentIndex == null) {
|
||||
return Duration.zero;
|
||||
}
|
||||
final globalPosition =
|
||||
position + _session!.audioTracks[currentIndex].startOffset;
|
||||
final chapter = _session!.findChapterAtTime(globalPosition);
|
||||
return globalPosition - chapter.start;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> togglePlayPause() {
|
||||
// check if book is set
|
||||
if (_session == null) {
|
||||
return Future.value();
|
||||
}
|
||||
|
||||
return switch (_player.playerState) {
|
||||
PlayerState(playing: var isPlaying) => isPlaying ? pause() : play(),
|
||||
};
|
||||
}
|
||||
|
||||
// 播放控制方法
|
||||
@override
|
||||
Future<void> play() => _player.play();
|
||||
Future<void> play() async {
|
||||
await _player.play();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pause() => _player.pause();
|
||||
Future<void> pause() async {
|
||||
await _player.pause();
|
||||
}
|
||||
|
||||
// 重写上一曲/下一曲为章节导航
|
||||
@override
|
||||
Future<void> skipToNext() async {
|
||||
if (_book == null) {
|
||||
if (_session == null) {
|
||||
// 回退到默认行为
|
||||
return _player.seekToNext();
|
||||
}
|
||||
|
|
@ -150,17 +186,17 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
// 回退到默认行为
|
||||
return _player.seekToNext();
|
||||
}
|
||||
final currentIndex = _book!.chapters.indexOf(chapter);
|
||||
if (currentIndex < _book!.chapters.length - 1) {
|
||||
final chapterIndex = _session!.chapters.indexOf(chapter);
|
||||
if (chapterIndex < _session!.chapters.length - 1) {
|
||||
// 跳到下一章
|
||||
final nextChapter = _book!.chapters[currentIndex + 1];
|
||||
final nextChapter = _session!.chapters[chapterIndex + 1];
|
||||
await skipToChapter(nextChapter.id);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> skipToPrevious() async {
|
||||
if (_book == null) {
|
||||
if (_session == null) {
|
||||
return _player.seekToPrevious();
|
||||
}
|
||||
|
||||
|
|
@ -168,14 +204,14 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
if (chapter == null) {
|
||||
return _player.seekToPrevious();
|
||||
}
|
||||
final currentIndex = _book!.chapters.indexOf(chapter);
|
||||
final currentIndex = _session!.chapters.indexOf(chapter);
|
||||
if (currentIndex > 0) {
|
||||
// 跳到上一章
|
||||
final prevChapter = _book!.chapters[currentIndex - 1];
|
||||
final prevChapter = _session!.chapters[currentIndex - 1];
|
||||
await skipToChapter(prevChapter.id);
|
||||
} else {
|
||||
// 已经是第一章,回到开头
|
||||
await seekToPosition(Duration.zero);
|
||||
await seekInBook(Duration.zero);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -188,15 +224,24 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
if (track != null) {
|
||||
startOffset = track.startOffset;
|
||||
}
|
||||
await seekToPosition(startOffset + position);
|
||||
await seekInBook(startOffset + position);
|
||||
}
|
||||
|
||||
Future<void> setVolume(double volume) async {
|
||||
await _player.setVolume(volume);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await _player.setSpeed(speed);
|
||||
}
|
||||
|
||||
// 核心功能:跳转到全局时间位置
|
||||
Future<void> seekToPosition(Duration globalPosition) async {
|
||||
if (_book == null) return;
|
||||
Future<void> seekInBook(Duration globalPosition) async {
|
||||
if (_session == null) return;
|
||||
// 找到目标音轨和在音轨内的位置
|
||||
final track = _book!.findTrackAtTime(globalPosition);
|
||||
final index = _book!.tracks.indexOf(track);
|
||||
final track = _session!.findTrackAtTime(globalPosition);
|
||||
final index = _session!.audioTracks.indexOf(track);
|
||||
Duration positionInTrack = globalPosition - track.startOffset;
|
||||
if (positionInTrack <= Duration.zero) {
|
||||
positionInTrack = offset;
|
||||
|
|
@ -205,13 +250,26 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
await _player.seek(positionInTrack, index: index);
|
||||
}
|
||||
|
||||
AudioPlayer get player => _player;
|
||||
PlaybackState _transformEvent(PlaybackEvent event) {
|
||||
return PlaybackState(
|
||||
controls: [
|
||||
MediaControl.skipToPrevious,
|
||||
if (kIsWeb || !Platform.isAndroid) MediaControl.skipToPrevious,
|
||||
MediaControl.rewind,
|
||||
if (_player.playing) MediaControl.pause else MediaControl.play,
|
||||
MediaControl.skipToNext,
|
||||
MediaControl.stop,
|
||||
MediaControl.fastForward,
|
||||
if (kIsWeb || !Platform.isAndroid) MediaControl.skipToNext,
|
||||
],
|
||||
systemActions: {
|
||||
if (kIsWeb || !Platform.isAndroid) MediaAction.skipToPrevious,
|
||||
MediaAction.rewind,
|
||||
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,
|
||||
|
|
@ -225,6 +283,7 @@ class HookAudioHandler extends BaseAudioHandler {
|
|||
bufferedPosition: _player.bufferedPosition,
|
||||
speed: _player.speed,
|
||||
queueIndex: event.currentIndex,
|
||||
captioningEnabled: false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -246,7 +305,7 @@ Uri _getUri(
|
|||
Uri.parse('${baseUrl.toString()}${track.contentUrl}?token=$token');
|
||||
}
|
||||
|
||||
extension BookExpandedExtension on BookExpanded {
|
||||
extension PlaybackSessionExpandedExtension on PlaybackSessionExpanded {
|
||||
BookChapter findChapterAtTime(Duration position) {
|
||||
return chapters.firstWhere(
|
||||
(element) {
|
||||
|
|
@ -257,16 +316,23 @@ extension BookExpandedExtension on BookExpanded {
|
|||
}
|
||||
|
||||
AudioTrack findTrackAtTime(Duration position) {
|
||||
return tracks.firstWhere(
|
||||
return audioTracks.firstWhere(
|
||||
(element) {
|
||||
return element.startOffset <= position &&
|
||||
element.startOffset + element.duration >= position + offset;
|
||||
},
|
||||
orElse: () => tracks.first,
|
||||
orElse: () => audioTracks.first,
|
||||
);
|
||||
}
|
||||
|
||||
int findTrackIndexAtTime(Duration position) {
|
||||
return audioTracks.indexWhere((element) {
|
||||
return element.startOffset <= position &&
|
||||
element.startOffset + element.duration >= position + offset;
|
||||
});
|
||||
}
|
||||
|
||||
Duration getTrackStartOffset(int index) {
|
||||
return tracks[index].startOffset;
|
||||
return audioTracks[index].startOffset;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,62 +1,62 @@
|
|||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:audio_session/audio_session.dart';
|
||||
import 'package:just_audio_background/just_audio_background.dart'
|
||||
show JustAudioBackground, NotificationConfig;
|
||||
import 'package:just_audio_media_kit/just_audio_media_kit.dart'
|
||||
show JustAudioMediaKit;
|
||||
import 'package:vaani/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/settings/models/app_settings.dart';
|
||||
// import 'package:audio_service/audio_service.dart';
|
||||
// import 'package:audio_session/audio_session.dart';
|
||||
// import 'package:just_audio_background/just_audio_background.dart'
|
||||
// show JustAudioBackground, NotificationConfig;
|
||||
// import 'package:just_audio_media_kit/just_audio_media_kit.dart'
|
||||
// show JustAudioMediaKit;
|
||||
// import 'package:vaani/settings/app_settings_provider.dart';
|
||||
// import 'package:vaani/settings/models/app_settings.dart';
|
||||
|
||||
Future<void> configurePlayer() async {
|
||||
// for playing audio on windows, linux
|
||||
JustAudioMediaKit.ensureInitialized(windows: false);
|
||||
// Future<void> configurePlayer() async {
|
||||
// // for playing audio on windows, linux
|
||||
// JustAudioMediaKit.ensureInitialized(windows: false);
|
||||
|
||||
// for configuring how this app will interact with other audio apps
|
||||
final session = await AudioSession.instance;
|
||||
await session.configure(const AudioSessionConfiguration.speech());
|
||||
// // for configuring how this app will interact with other audio apps
|
||||
// final session = await AudioSession.instance;
|
||||
// await session.configure(const AudioSessionConfiguration.speech());
|
||||
|
||||
final appSettings = loadOrCreateAppSettings();
|
||||
// final appSettings = loadOrCreateAppSettings();
|
||||
|
||||
// for playing audio in the background
|
||||
await JustAudioBackground.init(
|
||||
androidNotificationChannelId: 'com.vaani.bg_demo.channel.audio',
|
||||
androidNotificationChannelName: 'Audio playback',
|
||||
androidNotificationOngoing: false,
|
||||
androidStopForegroundOnPause: false,
|
||||
androidNotificationChannelDescription: 'Audio playback in the background',
|
||||
androidNotificationIcon: 'drawable/ic_stat_logo',
|
||||
rewindInterval: appSettings.notificationSettings.rewindInterval,
|
||||
fastForwardInterval: appSettings.notificationSettings.fastForwardInterval,
|
||||
androidShowNotificationBadge: false,
|
||||
notificationConfigBuilder: (state) {
|
||||
final controls = [
|
||||
if (appSettings.notificationSettings.mediaControls
|
||||
.contains(NotificationMediaControl.skipToPreviousChapter) &&
|
||||
state.hasPrevious)
|
||||
MediaControl.skipToPrevious,
|
||||
if (appSettings.notificationSettings.mediaControls
|
||||
.contains(NotificationMediaControl.rewind))
|
||||
MediaControl.rewind,
|
||||
if (state.playing) MediaControl.pause else MediaControl.play,
|
||||
if (appSettings.notificationSettings.mediaControls
|
||||
.contains(NotificationMediaControl.fastForward))
|
||||
MediaControl.fastForward,
|
||||
if (appSettings.notificationSettings.mediaControls
|
||||
.contains(NotificationMediaControl.skipToNextChapter) &&
|
||||
state.hasNext)
|
||||
MediaControl.skipToNext,
|
||||
if (appSettings.notificationSettings.mediaControls
|
||||
.contains(NotificationMediaControl.stop))
|
||||
MediaControl.stop,
|
||||
];
|
||||
return NotificationConfig(
|
||||
controls: controls,
|
||||
systemActions: const {
|
||||
MediaAction.seek,
|
||||
MediaAction.seekForward,
|
||||
MediaAction.seekBackward,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
// // for playing audio in the background
|
||||
// await JustAudioBackground.init(
|
||||
// androidNotificationChannelId: 'com.vaani.bg_demo.channel.audio',
|
||||
// androidNotificationChannelName: 'Audio playback',
|
||||
// androidNotificationOngoing: false,
|
||||
// androidStopForegroundOnPause: false,
|
||||
// androidNotificationChannelDescription: 'Audio playback in the background',
|
||||
// androidNotificationIcon: 'drawable/ic_stat_logo',
|
||||
// rewindInterval: appSettings.notificationSettings.rewindInterval,
|
||||
// fastForwardInterval: appSettings.notificationSettings.fastForwardInterval,
|
||||
// androidShowNotificationBadge: false,
|
||||
// notificationConfigBuilder: (state) {
|
||||
// final controls = [
|
||||
// if (appSettings.notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.skipToPreviousChapter) &&
|
||||
// state.hasPrevious)
|
||||
// MediaControl.skipToPrevious,
|
||||
// if (appSettings.notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.rewind))
|
||||
// MediaControl.rewind,
|
||||
// if (state.playing) MediaControl.pause else MediaControl.play,
|
||||
// if (appSettings.notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.fastForward))
|
||||
// MediaControl.fastForward,
|
||||
// if (appSettings.notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.skipToNextChapter) &&
|
||||
// state.hasNext)
|
||||
// MediaControl.skipToNext,
|
||||
// if (appSettings.notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.stop))
|
||||
// MediaControl.stop,
|
||||
// ];
|
||||
// return NotificationConfig(
|
||||
// controls: controls,
|
||||
// systemActions: const {
|
||||
// MediaAction.seek,
|
||||
// MediaAction.seekForward,
|
||||
// MediaAction.seekBackward,
|
||||
// },
|
||||
// );
|
||||
// },
|
||||
// );
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart' as shelfsdk;
|
||||
import 'package:vaani/api/api_provider.dart';
|
||||
import 'package:vaani/features/player/core/audiobook_player.dart' as core;
|
||||
|
||||
|
|
@ -38,9 +39,9 @@ class AudiobookPlayer extends _$AudiobookPlayer {
|
|||
ref.onDispose(player.dispose);
|
||||
|
||||
// bind notify listeners to the player
|
||||
player.playerStateStream.listen((_) {
|
||||
ref.notifyListeners();
|
||||
});
|
||||
// player.playerStateStream.listen((_) {
|
||||
// ref.notifyListeners();
|
||||
// });
|
||||
|
||||
_logger.finer('created player');
|
||||
|
||||
|
|
@ -51,6 +52,13 @@ class AudiobookPlayer extends _$AudiobookPlayer {
|
|||
await state.setSpeed(speed);
|
||||
ref.notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> setSourceAudiobook({
|
||||
required shelfsdk.BookExpanded book,
|
||||
shelfsdk.MediaProgress? userMediaProgress,
|
||||
}) async {
|
||||
ref.notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@riverpod
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ final simpleAudiobookPlayerProvider =
|
|||
);
|
||||
|
||||
typedef _$SimpleAudiobookPlayer = Notifier<core.AudiobookPlayer>;
|
||||
String _$audiobookPlayerHash() => r'0f180308067486896fec6a65a6afb0e6686ac4a0';
|
||||
String _$audiobookPlayerHash() => r'04448247e79c5d60b9fd6f98eeeb865f1e8d0ff8';
|
||||
|
||||
/// See also [AudiobookPlayer].
|
||||
@ProviderFor(AudiobookPlayer)
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ final _logger = Logger('CurrentlyPlayingProvider');
|
|||
@riverpod
|
||||
BookExpanded? currentlyPlayingBook(Ref ref) {
|
||||
try {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
return player.book;
|
||||
final book = ref.watch(simpleAudiobookPlayerProvider.select((v) => v.book));
|
||||
return book;
|
||||
} catch (e) {
|
||||
_logger.warning('Error getting currently playing book: $e');
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ part of 'currently_playing_provider.dart';
|
|||
// **************************************************************************
|
||||
|
||||
String _$currentlyPlayingBookHash() =>
|
||||
r'e4258694c8f0d1e89651b330fae0f672ca13a484';
|
||||
r'f2c47028340d253be9440dc29f835328ff30c0e6';
|
||||
|
||||
/// See also [currentlyPlayingBook].
|
||||
@ProviderFor(currentlyPlayingBook)
|
||||
|
|
|
|||
216
lib/features/player/providers/session_provider.dart
Normal file
216
lib/features/player/providers/session_provider.dart
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:just_audio_media_kit/just_audio_media_kit.dart';
|
||||
import 'package:riverpod/riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart' as core;
|
||||
import 'package:vaani/api/api_provider.dart';
|
||||
import 'package:vaani/api/library_item_provider.dart';
|
||||
import 'package:vaani/features/downloads/providers/download_manager.dart';
|
||||
import 'package:vaani/features/per_book_settings/providers/book_settings_provider.dart';
|
||||
import 'package:vaani/features/player/core/audiobook_player_session.dart';
|
||||
import 'package:vaani/globals.dart';
|
||||
import 'package:vaani/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/shared/extensions/obfuscation.dart';
|
||||
|
||||
part 'session_provider.g.dart';
|
||||
|
||||
class SessionPlayer {
|
||||
late final AbsAudioHandler _audioService;
|
||||
core.PlaybackSessionExpanded? _session;
|
||||
Ref ref;
|
||||
SessionPlayer(this.ref);
|
||||
void setAudioService(AbsAudioHandler audioPlayer) {
|
||||
_audioService = audioPlayer;
|
||||
}
|
||||
|
||||
Future<void> load(String id, String? episodeId) async {
|
||||
ref.read(sessionLoadingProvider(id).notifier).setLoading();
|
||||
final api = ref.read(authenticatedApiProvider);
|
||||
final playBack = await api.items.play(
|
||||
libraryItemId: id,
|
||||
parameters: core.PlayItemReqParams(
|
||||
deviceInfo: core.DeviceInfoReqParams(
|
||||
clientVersion: appVersion,
|
||||
manufacturer: deviceManufacturer,
|
||||
model: deviceModel,
|
||||
sdkVersion: deviceSdkVersion,
|
||||
clientName: appName,
|
||||
deviceName: deviceName,
|
||||
),
|
||||
forceDirectPlay: false,
|
||||
forceTranscode: false,
|
||||
supportedMimeTypes: [
|
||||
"audio/flac",
|
||||
"audio/mpeg",
|
||||
"audio/mp4",
|
||||
"audio/ogg",
|
||||
"audio/aac",
|
||||
"audio/webm",
|
||||
],
|
||||
),
|
||||
responseErrorHandler: _responseErrorHandler,
|
||||
) as core.PlaybackSessionExpanded;
|
||||
|
||||
final downloadManager = ref.read(simpleDownloadManagerProvider);
|
||||
final libItem =
|
||||
await ref.read(libraryItemProvider(playBack.libraryItemId).future);
|
||||
final downloadedUris = await downloadManager.getDownloadedFilesUri(libItem);
|
||||
|
||||
var bookPlayerSettings =
|
||||
ref.read(bookSettingsProvider(playBack.libraryItemId)).playerSettings;
|
||||
var appPlayerSettings = ref.read(appSettingsProvider).playerSettings;
|
||||
|
||||
var configurePlayerForEveryBook =
|
||||
appPlayerSettings.configurePlayerForEveryBook;
|
||||
|
||||
await Future.wait([
|
||||
_audioService.setSourceAudiobook(
|
||||
playBack,
|
||||
baseUrl: api.baseUrl,
|
||||
token: api.token!,
|
||||
downloadedUris: downloadedUris,
|
||||
),
|
||||
// set the volume
|
||||
_audioService.setVolume(
|
||||
configurePlayerForEveryBook
|
||||
? bookPlayerSettings.preferredDefaultVolume ??
|
||||
appPlayerSettings.preferredDefaultVolume
|
||||
: appPlayerSettings.preferredDefaultVolume,
|
||||
),
|
||||
// set the speed
|
||||
_audioService.setSpeed(
|
||||
configurePlayerForEveryBook
|
||||
? bookPlayerSettings.preferredDefaultSpeed ??
|
||||
appPlayerSettings.preferredDefaultSpeed
|
||||
: appPlayerSettings.preferredDefaultSpeed,
|
||||
),
|
||||
]);
|
||||
_session = playBack;
|
||||
ref.read(sessionLoadingProvider(id).notifier).setLoaded();
|
||||
ref.notifyListeners();
|
||||
}
|
||||
|
||||
AbsAudioHandler get audioService => _audioService;
|
||||
core.PlaybackSession? get session => _session;
|
||||
|
||||
void _responseErrorHandler(http.Response response, [error]) {
|
||||
if (response.statusCode != 200) {
|
||||
appLogger.severe('Error with api: ${response.obfuscate()}, $error');
|
||||
throw PlaybackSyncError(
|
||||
'Error syncing position: ${response.body}, $error',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class Player extends _$Player {
|
||||
@override
|
||||
AbsAudioHandler build() {
|
||||
final audioService = ref.watch(sessionProvider).audioService;
|
||||
// audioService.positionStream.listen((position){
|
||||
|
||||
// });
|
||||
return audioService;
|
||||
}
|
||||
|
||||
Future<void> togglePlayPause() => state.togglePlayPause();
|
||||
Future<void> play() => state.play();
|
||||
Future<void> pause() => state.pause();
|
||||
Future<void> seekInBook(Duration globalPosition) =>
|
||||
state.seekInBook(globalPosition);
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
SessionPlayer session(Ref ref) {
|
||||
return SessionPlayer(ref);
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class SessionLoading extends _$SessionLoading {
|
||||
@override
|
||||
bool build(String itemId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
setLoading() {
|
||||
state = true;
|
||||
}
|
||||
|
||||
setLoaded() {
|
||||
state = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class PlayState extends _$PlayState {
|
||||
@override
|
||||
PlayerState build() {
|
||||
return PlayerState(false, ProcessingState.idle);
|
||||
}
|
||||
|
||||
void setState(PlayerState playerState) {
|
||||
state = playerState;
|
||||
}
|
||||
}
|
||||
|
||||
@riverpod
|
||||
core.BookChapter? currentChapter(Ref ref) {
|
||||
return ref.watch(playerProvider.select((v) => v.currentChapter));
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<AbsAudioHandler> audioHandlerInit(Ref ref) async {
|
||||
// JustAudioMediaKit.ensureInitialized(windows: false);
|
||||
JustAudioMediaKit.ensureInitialized();
|
||||
final audioService = await AudioService.init(
|
||||
builder: () => AbsAudioHandler(ref),
|
||||
config: const AudioServiceConfig(
|
||||
androidNotificationChannelId: 'com.vaani.rang.channel.audio',
|
||||
androidNotificationChannelName: 'ABSPlayback',
|
||||
androidNotificationChannelDescription:
|
||||
'Needed to control audio from lock screen',
|
||||
androidNotificationOngoing: false,
|
||||
androidStopForegroundOnPause: false,
|
||||
androidNotificationIcon: 'drawable/ic_stat_logo',
|
||||
preloadArtwork: true,
|
||||
),
|
||||
);
|
||||
ref.read(sessionProvider).setAudioService(audioService);
|
||||
return audioService;
|
||||
}
|
||||
|
||||
// @Riverpod(keepAlive: true)
|
||||
// class PlaybackReporter extends _$PlaybackReporter {
|
||||
// @override
|
||||
// Future<core.PlaybackReporter> build() async {
|
||||
// final playerSettings = ref.watch(appSettingsProvider).playerSettings;
|
||||
// final player = ref.watch(playerProvider);
|
||||
// final session = ref.watch(sessionProvider.select((v) => v.session));
|
||||
// final api = ref.watch(authenticatedApiProvider);
|
||||
|
||||
// final reporter = core.PlaybackReporter(
|
||||
// player.player,
|
||||
// api,
|
||||
// reportingInterval: playerSettings.playbackReportInterval,
|
||||
// markCompleteWhenTimeLeft: playerSettings.markCompleteWhenTimeLeft,
|
||||
// minimumPositionForReporting: playerSettings.minimumPositionForReporting,
|
||||
// session: session,
|
||||
// );
|
||||
// ref.onDispose(reporter.dispose);
|
||||
// return reporter;
|
||||
// }
|
||||
// }
|
||||
|
||||
class PlaybackSyncError implements Exception {
|
||||
String message;
|
||||
|
||||
PlaybackSyncError([this.message = 'Error syncing playback']);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'PlaybackSyncError: $message';
|
||||
}
|
||||
}
|
||||
253
lib/features/player/providers/session_provider.g.dart
Normal file
253
lib/features/player/providers/session_provider.g.dart
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'session_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$sessionHash() => r'ae97659a7772abaa3c97644f39af6b3f05c75faf';
|
||||
|
||||
/// See also [session].
|
||||
@ProviderFor(session)
|
||||
final sessionProvider = Provider<SessionPlayer>.internal(
|
||||
session,
|
||||
name: r'sessionProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$sessionHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef SessionRef = ProviderRef<SessionPlayer>;
|
||||
String _$currentChapterHash() => r'a2f43d62f77ce48e6ca34c89700443f67dbd78fe';
|
||||
|
||||
/// See also [currentChapter].
|
||||
@ProviderFor(currentChapter)
|
||||
final currentChapterProvider = AutoDisposeProvider<core.BookChapter?>.internal(
|
||||
currentChapter,
|
||||
name: r'currentChapterProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$currentChapterHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef CurrentChapterRef = AutoDisposeProviderRef<core.BookChapter?>;
|
||||
String _$audioHandlerInitHash() => r'64bc78439049068ec6de6e19af657d410bde9581';
|
||||
|
||||
/// See also [audioHandlerInit].
|
||||
@ProviderFor(audioHandlerInit)
|
||||
final audioHandlerInitProvider = FutureProvider<AbsAudioHandler>.internal(
|
||||
audioHandlerInit,
|
||||
name: r'audioHandlerInitProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$audioHandlerInitHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef AudioHandlerInitRef = FutureProviderRef<AbsAudioHandler>;
|
||||
String _$playerHash() => r'41cc626fd4a3317ce7e1ffa3c5e03206a9819231';
|
||||
|
||||
/// See also [Player].
|
||||
@ProviderFor(Player)
|
||||
final playerProvider = NotifierProvider<Player, AbsAudioHandler>.internal(
|
||||
Player.new,
|
||||
name: r'playerProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$playerHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$Player = Notifier<AbsAudioHandler>;
|
||||
String _$sessionLoadingHash() => r'4688469dd8ac9f38063917ede032cfe1506a63a8';
|
||||
|
||||
/// Copied from Dart SDK
|
||||
class _SystemHash {
|
||||
_SystemHash._();
|
||||
|
||||
static int combine(int hash, int value) {
|
||||
// ignore: parameter_assignments
|
||||
hash = 0x1fffffff & (hash + value);
|
||||
// ignore: parameter_assignments
|
||||
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
|
||||
return hash ^ (hash >> 6);
|
||||
}
|
||||
|
||||
static int finish(int hash) {
|
||||
// ignore: parameter_assignments
|
||||
hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
|
||||
// ignore: parameter_assignments
|
||||
hash = hash ^ (hash >> 11);
|
||||
return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
|
||||
}
|
||||
}
|
||||
|
||||
abstract class _$SessionLoading extends BuildlessNotifier<bool> {
|
||||
late final String itemId;
|
||||
|
||||
bool build(
|
||||
String itemId,
|
||||
);
|
||||
}
|
||||
|
||||
/// See also [SessionLoading].
|
||||
@ProviderFor(SessionLoading)
|
||||
const sessionLoadingProvider = SessionLoadingFamily();
|
||||
|
||||
/// See also [SessionLoading].
|
||||
class SessionLoadingFamily extends Family<bool> {
|
||||
/// See also [SessionLoading].
|
||||
const SessionLoadingFamily();
|
||||
|
||||
/// See also [SessionLoading].
|
||||
SessionLoadingProvider call(
|
||||
String itemId,
|
||||
) {
|
||||
return SessionLoadingProvider(
|
||||
itemId,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
SessionLoadingProvider getProviderOverride(
|
||||
covariant SessionLoadingProvider provider,
|
||||
) {
|
||||
return call(
|
||||
provider.itemId,
|
||||
);
|
||||
}
|
||||
|
||||
static const Iterable<ProviderOrFamily>? _dependencies = null;
|
||||
|
||||
@override
|
||||
Iterable<ProviderOrFamily>? get dependencies => _dependencies;
|
||||
|
||||
static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null;
|
||||
|
||||
@override
|
||||
Iterable<ProviderOrFamily>? get allTransitiveDependencies =>
|
||||
_allTransitiveDependencies;
|
||||
|
||||
@override
|
||||
String? get name => r'sessionLoadingProvider';
|
||||
}
|
||||
|
||||
/// See also [SessionLoading].
|
||||
class SessionLoadingProvider
|
||||
extends NotifierProviderImpl<SessionLoading, bool> {
|
||||
/// See also [SessionLoading].
|
||||
SessionLoadingProvider(
|
||||
String itemId,
|
||||
) : this._internal(
|
||||
() => SessionLoading()..itemId = itemId,
|
||||
from: sessionLoadingProvider,
|
||||
name: r'sessionLoadingProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$sessionLoadingHash,
|
||||
dependencies: SessionLoadingFamily._dependencies,
|
||||
allTransitiveDependencies:
|
||||
SessionLoadingFamily._allTransitiveDependencies,
|
||||
itemId: itemId,
|
||||
);
|
||||
|
||||
SessionLoadingProvider._internal(
|
||||
super._createNotifier, {
|
||||
required super.name,
|
||||
required super.dependencies,
|
||||
required super.allTransitiveDependencies,
|
||||
required super.debugGetCreateSourceHash,
|
||||
required super.from,
|
||||
required this.itemId,
|
||||
}) : super.internal();
|
||||
|
||||
final String itemId;
|
||||
|
||||
@override
|
||||
bool runNotifierBuild(
|
||||
covariant SessionLoading notifier,
|
||||
) {
|
||||
return notifier.build(
|
||||
itemId,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Override overrideWith(SessionLoading Function() create) {
|
||||
return ProviderOverride(
|
||||
origin: this,
|
||||
override: SessionLoadingProvider._internal(
|
||||
() => create()..itemId = itemId,
|
||||
from: from,
|
||||
name: null,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
debugGetCreateSourceHash: null,
|
||||
itemId: itemId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
NotifierProviderElement<SessionLoading, bool> createElement() {
|
||||
return _SessionLoadingProviderElement(this);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is SessionLoadingProvider && other.itemId == itemId;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
var hash = _SystemHash.combine(0, runtimeType.hashCode);
|
||||
hash = _SystemHash.combine(hash, itemId.hashCode);
|
||||
|
||||
return _SystemHash.finish(hash);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
mixin SessionLoadingRef on NotifierProviderRef<bool> {
|
||||
/// The parameter `itemId` of this provider.
|
||||
String get itemId;
|
||||
}
|
||||
|
||||
class _SessionLoadingProviderElement
|
||||
extends NotifierProviderElement<SessionLoading, bool>
|
||||
with SessionLoadingRef {
|
||||
_SessionLoadingProviderElement(super.provider);
|
||||
|
||||
@override
|
||||
String get itemId => (origin as SessionLoadingProvider).itemId;
|
||||
}
|
||||
|
||||
String _$playStateHash() => r'5256c4154c4254e406593035bc54d917a9a059bf';
|
||||
|
||||
/// See also [PlayState].
|
||||
@ProviderFor(PlayState)
|
||||
final playStateProvider = NotifierProvider<PlayState, PlayerState>.internal(
|
||||
PlayState.new,
|
||||
name: r'playStateProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$playStateHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$PlayState = Notifier<PlayerState>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
|
|
@ -3,10 +3,8 @@ import 'dart:math';
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/api/image_provider.dart';
|
||||
import 'package:vaani/api/library_item_provider.dart';
|
||||
import 'package:vaani/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/currently_playing_provider.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/features/player/view/widgets/player_player_pause_button.dart';
|
||||
import 'package:vaani/features/player/view/widgets/player_progress_bar.dart';
|
||||
import 'package:vaani/features/skip_start_end/player_skip_chapter_start_end.dart';
|
||||
|
|
@ -28,32 +26,20 @@ class PlayerExpanded extends HookConsumerWidget {
|
|||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final session = ref.watch(sessionProvider).session;
|
||||
if (session == null) {
|
||||
return SizedBox.shrink();
|
||||
}
|
||||
|
||||
/// all the properties that help in building the widget are calculated from the [percentageExpandedPlayer]
|
||||
/// however, some properties need to start later than 0% and end before 100%
|
||||
final currentBook = ref.watch(currentlyPlayingBookProvider);
|
||||
if (currentBook == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final currentChapter = ref.watch(currentPlayingChapterProvider);
|
||||
final currentBookMetadata = ref.watch(currentBookMetadataProvider);
|
||||
final currentChapter = ref.watch(currentChapterProvider);
|
||||
// final currentBookMetadata = ref.watch(currentBookMetadataProvider);
|
||||
// max height of the player is the height of the screen
|
||||
final playerMaxHeight = MediaQuery.of(context).size.height;
|
||||
final availWidth = MediaQuery.of(context).size.width;
|
||||
// the image width when the player is expanded
|
||||
final imageSize = min(playerMaxHeight * 0.5, availWidth * 0.9);
|
||||
final itemBeingPlayed =
|
||||
ref.watch(libraryItemProvider(currentBook.libraryItemId));
|
||||
final imageOfItemBeingPlayed = itemBeingPlayed.valueOrNull != null
|
||||
? ref.watch(
|
||||
coverImageProvider(itemBeingPlayed.valueOrNull!.id),
|
||||
)
|
||||
: null;
|
||||
final imgWidget = imageOfItemBeingPlayed?.valueOrNull != null
|
||||
? Image.memory(
|
||||
imageOfItemBeingPlayed!.valueOrNull!,
|
||||
fit: BoxFit.cover,
|
||||
)
|
||||
: const BookCoverSkeleton();
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
|
|
@ -104,7 +90,7 @@ class PlayerExpanded extends HookConsumerWidget {
|
|||
borderRadius: BorderRadius.circular(
|
||||
AppElementSizes.borderRadiusRegular,
|
||||
),
|
||||
child: imgWidget,
|
||||
child: BookCoverWidget(),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
|
@ -133,8 +119,8 @@ class PlayerExpanded extends HookConsumerWidget {
|
|||
padding: EdgeInsets.only(bottom: AppElementSizes.paddingRegular),
|
||||
child: Text(
|
||||
[
|
||||
currentBookMetadata?.title ?? '',
|
||||
currentBookMetadata?.authorName ?? '',
|
||||
session.displayTitle,
|
||||
session.displayAuthor,
|
||||
].join(' - '),
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
color: Theme.of(context)
|
||||
|
|
|
|||
|
|
@ -1,13 +1,9 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/src/widgets/framework.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/api/image_provider.dart';
|
||||
import 'package:vaani/api/library_item_provider.dart';
|
||||
import 'package:vaani/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
import 'package:vaani/features/player/providers/currently_playing_provider.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/features/player/view/widgets/player_player_pause_button.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
import 'package:vaani/shared/widgets/shelves/book_shelf.dart';
|
||||
|
|
@ -20,25 +16,11 @@ class PlayerMinimized extends HookConsumerWidget {
|
|||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final currentBook = ref.watch(currentlyPlayingBookProvider);
|
||||
if (currentBook == null) {
|
||||
return const SizedBox.shrink();
|
||||
final session = ref.watch(sessionProvider).session;
|
||||
if (session == null) {
|
||||
return SizedBox.shrink();
|
||||
}
|
||||
final itemBeingPlayed =
|
||||
ref.watch(libraryItemProvider(currentBook.libraryItemId));
|
||||
final imageOfItemBeingPlayed = itemBeingPlayed.valueOrNull != null
|
||||
? ref.watch(
|
||||
coverImageProvider(itemBeingPlayed.valueOrNull!.id),
|
||||
)
|
||||
: null;
|
||||
final imgWidget = imageOfItemBeingPlayed?.valueOrNull != null
|
||||
? Image.memory(
|
||||
imageOfItemBeingPlayed!.valueOrNull!,
|
||||
fit: BoxFit.cover,
|
||||
)
|
||||
: const BookCoverSkeleton();
|
||||
final bookMetaExpanded = ref.watch(currentBookMetadataProvider);
|
||||
final currentChapter = ref.watch(currentPlayingChapterProvider);
|
||||
final currentChapter = ref.watch(currentChapterProvider);
|
||||
|
||||
return PlayerMinimizedFramework(
|
||||
children: [
|
||||
|
|
@ -51,7 +33,7 @@ class PlayerMinimized extends HookConsumerWidget {
|
|||
context.pushNamed(
|
||||
Routes.libraryItem.name,
|
||||
pathParameters: {
|
||||
Routes.libraryItem.pathParamName!: currentBook.libraryItemId,
|
||||
Routes.libraryItem.pathParamName!: session.libraryItemId,
|
||||
},
|
||||
);
|
||||
},
|
||||
|
|
@ -59,7 +41,7 @@ class PlayerMinimized extends HookConsumerWidget {
|
|||
constraints: BoxConstraints(
|
||||
maxWidth: playerMinimizedHeight,
|
||||
),
|
||||
child: imgWidget,
|
||||
child: BookCoverWidget(),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
|
@ -76,14 +58,14 @@ class PlayerMinimized extends HookConsumerWidget {
|
|||
children: [
|
||||
// AutoScrollText(
|
||||
Text(
|
||||
'${bookMetaExpanded?.title ?? ''} - ${currentChapter?.title ?? ''}',
|
||||
'${session.displayTitle} - ${currentChapter?.title ?? ''}',
|
||||
maxLines: 1, overflow: TextOverflow.ellipsis,
|
||||
// velocity:
|
||||
// const Velocity(pixelsPerSecond: Offset(16, 0)),
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
Text(
|
||||
bookMetaExpanded?.authorName ?? '',
|
||||
session.displayAuthor,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
|
||||
|
|
@ -127,9 +109,9 @@ class PlayerMinimizedFramework extends HookConsumerWidget {
|
|||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
final player = ref.watch(playerProvider);
|
||||
final progress =
|
||||
useStream(player.positionStream, initialData: Duration.zero);
|
||||
useStream(player.positionStreamInChapter, initialData: Duration.zero);
|
||||
return GestureDetector(
|
||||
onTap: () => context.pushNamed(Routes.player.name),
|
||||
child: Container(
|
||||
|
|
@ -147,7 +129,7 @@ class PlayerMinimizedFramework extends HookConsumerWidget {
|
|||
// value: (progress.data ?? Duration.zero).inSeconds /
|
||||
// player.book!.duration.inSeconds,
|
||||
value: (progress.data ?? Duration.zero).inSeconds /
|
||||
(player.duration?.inSeconds ?? 1),
|
||||
(player.chapterDuration?.inSeconds ?? 1),
|
||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:vaani/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
|
||||
class AudiobookPlayerPlayPauseButton extends HookConsumerWidget {
|
||||
const AudiobookPlayerPlayPauseButton({
|
||||
|
|
@ -15,18 +14,18 @@ class AudiobookPlayerPlayPauseButton extends HookConsumerWidget {
|
|||
final double iconSize;
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
final playing = ref.watch(isPlayerPlayingProvider);
|
||||
final playState = ref.watch(playStateProvider);
|
||||
final player = ref.read(playerProvider.notifier);
|
||||
final playPauseController = useAnimationController(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
initialValue: 1,
|
||||
);
|
||||
if (playing) {
|
||||
if (playState.playing) {
|
||||
playPauseController.forward();
|
||||
} else {
|
||||
playPauseController.reverse();
|
||||
}
|
||||
return switch (player.processingState) {
|
||||
return switch (playState.processingState) {
|
||||
ProcessingState.loading || ProcessingState.buffering => const Padding(
|
||||
padding: EdgeInsets.all(AppElementSizes.paddingRegular),
|
||||
child: CircularProgressIndicator(),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue