mirror of
https://github.com/Dr-Blank/Vaani.git
synced 2026-02-16 14:29:35 +00:00
一堆乱七八糟的修改
播放页面增加桌面版
This commit is contained in:
parent
aee1fbde88
commit
3ba35b31b8
116 changed files with 1238 additions and 2592 deletions
|
|
@ -1,240 +1,239 @@
|
|||
/// a wrapper around the audioplayers package to manage the audio player instance
|
||||
///
|
||||
/// this is needed as audiobook can be a list of audio files instead of a single file
|
||||
library;
|
||||
// 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:just_audio_background/just_audio_background.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
|
||||
import 'package:vaani/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/settings/models/app_settings.dart';
|
||||
import 'package:vaani/shared/extensions/model_conversions.dart';
|
||||
|
||||
final _logger = Logger('AudiobookPlayer');
|
||||
import 'package:vaani/features/player/core/player_status.dart' as core;
|
||||
import 'package:vaani/features/player/providers/player_status_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);
|
||||
|
||||
/// time into the current chapter to determine if we should go to the previous chapter or the start of the current chapter
|
||||
final doNotSeekBackIfLessThan = Duration(seconds: 5);
|
||||
class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
|
||||
final AudioPlayer _player = AudioPlayer();
|
||||
// final List<AudioSource> _playlist = [];
|
||||
final Ref ref;
|
||||
|
||||
/// returns the sum of the duration of all the previous tracks before the [index]
|
||||
Duration sumOfTracks(BookExpanded book, int? index) {
|
||||
_logger.fine('Calculating sum of tracks for index: $index');
|
||||
// return 0 if index is less than 0
|
||||
if (index == null || index < 0) {
|
||||
_logger.warning('Index is null or less than 0, returning 0');
|
||||
return Duration.zero;
|
||||
}
|
||||
final total = book.tracks.sublist(0, index).fold<Duration>(
|
||||
Duration.zero,
|
||||
(previousValue, element) => previousValue + element.duration,
|
||||
);
|
||||
_logger.fine('Sum of tracks for index: $index is $total');
|
||||
return total;
|
||||
}
|
||||
PlaybackSessionExpanded? _session;
|
||||
|
||||
/// will manage the audio player instance
|
||||
class AudiobookPlayer extends AudioPlayer {
|
||||
// constructor which takes in the BookExpanded object
|
||||
AudiobookPlayer(this.token, this.baseUrl) : super() {
|
||||
// set the source of the player to the first track in the book
|
||||
_logger.config('Setting up audiobook player');
|
||||
// playerStateStream.listen((playerState) {
|
||||
// if (playerState.processingState == ProcessingState.completed) {
|
||||
// Future.microtask(seekToNext);
|
||||
// }
|
||||
// });
|
||||
final _currentChapterObject = BehaviorSubject<BookChapter?>.seeded(null);
|
||||
AbsAudioHandler(this.ref) {
|
||||
_setupAudioPlayer();
|
||||
}
|
||||
|
||||
/// the [BookExpanded] being played
|
||||
BookExpanded? _book;
|
||||
void _setupAudioPlayer() {
|
||||
final statusNotifier = ref.read(playerStatusProvider.notifier);
|
||||
|
||||
// /// the [BookExpanded] trying to be played
|
||||
// BookExpanded? _intended_book;
|
||||
|
||||
/// the [BookExpanded] being played
|
||||
///
|
||||
/// to set the book, use [setSourceAudiobook]
|
||||
BookExpanded? get book => _book;
|
||||
|
||||
/// the authentication token to access the [AudioTrack.contentUrl]
|
||||
final String token;
|
||||
|
||||
/// the base url for the audio files
|
||||
final Uri baseUrl;
|
||||
|
||||
// the current index of the audio file in the [book]
|
||||
// int _currentIndex = 0;
|
||||
|
||||
// available audio tracks
|
||||
int? get availableTracks => _book?.tracks.length;
|
||||
|
||||
/// sets the current [AudioTrack] as the source of the player
|
||||
Future<void> setSourceAudiobook(
|
||||
BookExpanded? book, {
|
||||
bool preload = true,
|
||||
int? initialIndex,
|
||||
Duration? initialPosition,
|
||||
List<Uri>? downloadedUris,
|
||||
Uri? artworkUri,
|
||||
}) async {
|
||||
_logger.finer(
|
||||
'Initial position: $initialPosition, Downloaded URIs: $downloadedUris',
|
||||
);
|
||||
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;
|
||||
}
|
||||
_logger.info('Setting source for book: $book');
|
||||
|
||||
_logger.fine('Stopping player');
|
||||
await stop();
|
||||
|
||||
_book = book;
|
||||
// some calculations to set the initial index and position
|
||||
// initialPosition is of the entire book not just the current track
|
||||
// hence first we need to calculate the current track which will be used to set the initial position
|
||||
// then we set the initial index to the current track index and position as the remaining duration from the position
|
||||
// after subtracting the duration of all the previous tracks
|
||||
// initialPosition ;
|
||||
final trackToPlay =
|
||||
_book!.findTrackAtTime(initialPosition ?? Duration.zero);
|
||||
|
||||
final initialIndex = book.tracks.indexOf(trackToPlay);
|
||||
final initialPositionInTrack = initialPosition != null
|
||||
? initialPosition - trackToPlay.startOffset
|
||||
: null;
|
||||
_logger.finer('Setting audioSource');
|
||||
final playlist = book.tracks.map((track) {
|
||||
final retrievedUri =
|
||||
_getUri(track, downloadedUris, baseUrl: baseUrl, token: token);
|
||||
// _logger.fine(
|
||||
// 'Setting source for track: ${track.title}, URI: ${retrievedUri.obfuscate()}',
|
||||
// );
|
||||
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',
|
||||
// ),
|
||||
// ),
|
||||
);
|
||||
}).toList();
|
||||
await setAudioSources(
|
||||
playlist,
|
||||
preload: preload,
|
||||
initialIndex: initialIndex,
|
||||
initialPosition: initialPositionInTrack,
|
||||
).catchError((error) {
|
||||
_logger.shout('Error in setting audio source: $error');
|
||||
return null;
|
||||
// 转发播放状态
|
||||
_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 = _session?.findChapterAtTime(positionInBook);
|
||||
if (chapter != currentChapter) {
|
||||
_currentChapterObject.sink.add(chapter);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// toggles the player between play and pause
|
||||
Future<void> togglePlayPause() {
|
||||
// check if book is set
|
||||
if (_book == null) {
|
||||
_logger.warning('No book is set, not toggling play/pause');
|
||||
// 加载有声书
|
||||
Future<void> setSourceAudiobook(
|
||||
PlaybackSessionExpanded playbackSession, {
|
||||
required Uri baseUrl,
|
||||
required String token,
|
||||
List<Uri>? downloadedUris,
|
||||
}) async {
|
||||
_session = playbackSession;
|
||||
|
||||
// 添加所有音轨
|
||||
List<AudioSource> audioSources = [];
|
||||
for (final track in playbackSession.audioTracks) {
|
||||
audioSources.add(
|
||||
AudioSource.uri(
|
||||
_getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// TODO refactor this to cover all the states
|
||||
return switch (playerState) {
|
||||
PlayerState(playing: var isPlaying) => isPlaying ? pause() : play(),
|
||||
};
|
||||
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 seekInBook(initialPosition);
|
||||
// }
|
||||
}
|
||||
|
||||
/// need to override getDuration and getCurrentPosition to return according to the book instead of the current track
|
||||
/// this is because the book can be a list of audio files and the player is only aware of the current track
|
||||
/// so we need to calculate the duration and current position based on the book
|
||||
Future<void> seekInBook(Duration globalPosition) async {
|
||||
if (_book == null) {
|
||||
_logger.warning('No book is set, not seeking');
|
||||
return;
|
||||
}
|
||||
// 找到目标音轨和在音轨内的位置
|
||||
final track = _book!.findTrackAtTime(globalPosition);
|
||||
final index = _book!.tracks.indexOf(track);
|
||||
Duration positionInTrack = globalPosition - track.startOffset;
|
||||
if (positionInTrack <= Duration.zero) {
|
||||
positionInTrack = offset;
|
||||
}
|
||||
// 切换到目标音轨具体位置
|
||||
if (index != currentIndex) {
|
||||
await seek(positionInTrack, index: index);
|
||||
}
|
||||
await seek(positionInTrack);
|
||||
}
|
||||
// // 音轨切换处理
|
||||
// void _onTrackChanged(int trackIndex) {
|
||||
// if (_book == null) return;
|
||||
|
||||
// // 可以在这里处理音轨切换逻辑,比如预加载下一音轨
|
||||
// // print('切换到音轨: ${_book!.tracks[trackIndex].title}');
|
||||
// }
|
||||
|
||||
// 核心功能:跳转到指定章节
|
||||
Future<void> skipToChapter(int chapterId, {Duration? position}) async {
|
||||
if (_book == null) return;
|
||||
Future<void> skipToChapter(int chapterId) async {
|
||||
if (_session == null) return;
|
||||
|
||||
final chapter = _book!.chapters.firstWhere(
|
||||
final chapter = _session!.chapters.firstWhere(
|
||||
(ch) => ch.id == chapterId,
|
||||
orElse: () => throw Exception('Chapter not found'),
|
||||
);
|
||||
if (position != null) {
|
||||
print('章节开头: ${chapter.start}');
|
||||
print('章节开头: ${chapter.start + position}');
|
||||
await seekInBook(chapter.start + position);
|
||||
return;
|
||||
}
|
||||
await seekInBook(chapter.start + offset);
|
||||
}
|
||||
|
||||
PlaybackSessionExpanded? get session => _session;
|
||||
|
||||
// 当前音轨
|
||||
AudioTrack? get currentTrack {
|
||||
if (_session == null || _player.currentIndex == null) {
|
||||
return null;
|
||||
}
|
||||
return _session!.audioTracks[_player.currentIndex!];
|
||||
}
|
||||
|
||||
// 当前章节
|
||||
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 positionInBook {
|
||||
return _player.position + (currentTrack?.startOffset ?? Duration.zero);
|
||||
}
|
||||
|
||||
Duration get bufferedPositionInBook {
|
||||
return _player.bufferedPosition +
|
||||
(currentTrack?.startOffset ?? Duration.zero);
|
||||
}
|
||||
|
||||
Duration? get chapterDuration => currentChapter?.duration;
|
||||
|
||||
Stream<PlayerState> get playerStateStream => _player.playerStateStream;
|
||||
|
||||
Stream<Duration> get positionStream => _player.positionStream;
|
||||
|
||||
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 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<BookChapter?> get chapterStream => _currentChapterObject.stream;
|
||||
|
||||
Future<void> togglePlayPause() async {
|
||||
// check if book is set
|
||||
if (_session == null) {
|
||||
return Future.value();
|
||||
}
|
||||
_player.playerState.playing ? await pause() : await play();
|
||||
}
|
||||
|
||||
// 播放控制方法
|
||||
@override
|
||||
Future<void> seekToNext() async {
|
||||
if (_book == null) {
|
||||
Future<void> play() async {
|
||||
await _player.play();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pause() async {
|
||||
await _player.pause();
|
||||
}
|
||||
|
||||
// 重写上一曲/下一曲为章节导航
|
||||
@override
|
||||
Future<void> skipToNext() async {
|
||||
if (_session == null) {
|
||||
// 回退到默认行为
|
||||
return super.seekToNext();
|
||||
return _player.seekToNext();
|
||||
}
|
||||
final chapter = currentChapter;
|
||||
if (chapter == null) {
|
||||
// 回退到默认行为
|
||||
return super.seekToNext();
|
||||
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> seekToPrevious() async {
|
||||
if (_book == null) {
|
||||
return super.seekToPrevious();
|
||||
}
|
||||
|
||||
Future<void> skipToPrevious() async {
|
||||
final chapter = currentChapter;
|
||||
if (chapter == null) {
|
||||
return super.seekToPrevious();
|
||||
if (_session == null || 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 {
|
||||
// 已经是第一章,回到开头
|
||||
|
|
@ -242,84 +241,77 @@ class AudiobookPlayer extends AudioPlayer {
|
|||
}
|
||||
}
|
||||
|
||||
/// a convenience method to get position in the book instead of the current track position
|
||||
Duration get positionInBook {
|
||||
if (_book == null || currentIndex == null) {
|
||||
return Duration.zero;
|
||||
@override
|
||||
Future<void> seek(Duration position) async {
|
||||
// 这个 position 是当前音轨内的位置,我们不直接使用
|
||||
// 而是通过全局位置来控制
|
||||
final track = currentTrack;
|
||||
Duration startOffset = Duration.zero;
|
||||
if (track != null) {
|
||||
startOffset = track.startOffset;
|
||||
}
|
||||
return position + _book!.tracks[currentIndex!].startOffset;
|
||||
// return position + _book!.tracks[sequenceState!.currentIndex].startOffset;
|
||||
await seekInBook(startOffset + position);
|
||||
}
|
||||
|
||||
/// a convenience method to get the buffered position in the book instead of the current track position
|
||||
Duration get bufferedPositionInBook {
|
||||
if (_book == null || currentIndex == null) {
|
||||
return Duration.zero;
|
||||
Future<void> setVolume(double volume) async {
|
||||
await _player.setVolume(volume);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await _player.setSpeed(speed);
|
||||
}
|
||||
|
||||
// 核心功能:跳转到全局时间位置
|
||||
Future<void> seekInBook(Duration globalPosition) async {
|
||||
if (_session == null) return;
|
||||
// 找到目标音轨和在音轨内的位置
|
||||
final track = _session!.findTrackAtTime(globalPosition);
|
||||
final index = _session!.audioTracks.indexOf(track);
|
||||
Duration positionInTrack = globalPosition - track.startOffset;
|
||||
if (positionInTrack < Duration.zero) {
|
||||
positionInTrack = Duration.zero;
|
||||
}
|
||||
return bufferedPosition + _book!.tracks[currentIndex!].startOffset;
|
||||
// return bufferedPosition + _book!.tracks[sequenceState!.currentIndex].startOffset;
|
||||
// 切换到目标音轨具体位置
|
||||
await _player.seek(positionInTrack, index: index);
|
||||
}
|
||||
|
||||
// 章节进度
|
||||
Stream<Duration> get positionStreamInChapter {
|
||||
return super.positionStream.map((position) {
|
||||
if (_book == null || currentIndex == null) {
|
||||
return Duration.zero;
|
||||
}
|
||||
final globalPosition =
|
||||
position + _book!.tracks[currentIndex!].startOffset;
|
||||
final chapter = _book!.findChapterAtTime(globalPosition);
|
||||
return globalPosition - chapter.start;
|
||||
});
|
||||
}
|
||||
|
||||
/// streams to override to suit the book instead of the current track
|
||||
// - positionStream
|
||||
// - bufferedPositionStream
|
||||
Stream<Duration> get positionStreamInBook {
|
||||
// return the positionInBook stream
|
||||
return super.positionStream.map((position) {
|
||||
if (_book == null || currentIndex == null) {
|
||||
return Duration.zero;
|
||||
}
|
||||
return position + _book!.tracks[currentIndex!].startOffset;
|
||||
// return position + _book!.tracks[sequenceState!.currentIndex].startOffset;
|
||||
});
|
||||
}
|
||||
|
||||
Stream<Duration> get bufferedPositionStreamInBook {
|
||||
return super.bufferedPositionStream.map((position) {
|
||||
if (_book == null || currentIndex == null) {
|
||||
return Duration.zero;
|
||||
}
|
||||
return position + _book!.tracks[currentIndex!].startOffset;
|
||||
// return position + _book!.tracks[sequenceState!.currentIndex].startOffset;
|
||||
});
|
||||
}
|
||||
|
||||
/// a convenience getter for slow position stream
|
||||
Stream<Duration> get slowPositionStreamInBook {
|
||||
final superPositionStream = createPositionStream(
|
||||
steps: 100,
|
||||
minPeriod: const Duration(milliseconds: 500),
|
||||
maxPeriod: const Duration(seconds: 1),
|
||||
AudioPlayer get player => _player;
|
||||
PlaybackState _transformEvent(PlaybackEvent event) {
|
||||
return PlaybackState(
|
||||
controls: [
|
||||
if (kIsWeb || !Platform.isAndroid) MediaControl.skipToPrevious,
|
||||
MediaControl.rewind,
|
||||
if (_player.playing) MediaControl.pause else MediaControl.play,
|
||||
MediaControl.stop,
|
||||
MediaControl.fastForward,
|
||||
if (kIsWeb || !Platform.isAndroid) MediaControl.skipToNext,
|
||||
],
|
||||
systemActions: {
|
||||
if (kIsWeb || !Platform.isAndroid) MediaAction.skipToPrevious,
|
||||
MediaAction.rewind,
|
||||
MediaAction.seek,
|
||||
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: _player.position,
|
||||
bufferedPosition: event.bufferedPosition,
|
||||
speed: _player.speed,
|
||||
queueIndex: event.currentIndex,
|
||||
captioningEnabled: false,
|
||||
);
|
||||
// now we need to map the position to the book instead of the current track
|
||||
return superPositionStream.map((position) {
|
||||
if (_book == null || currentIndex == null) {
|
||||
return Duration.zero;
|
||||
}
|
||||
return position + _book!.tracks[currentIndex!].startOffset;
|
||||
// return position + _book!.tracks[sequenceState!.currentIndex].startOffset;
|
||||
});
|
||||
}
|
||||
|
||||
/// get current chapter
|
||||
BookChapter? get currentChapter {
|
||||
if (_book == null) {
|
||||
return null;
|
||||
}
|
||||
return _book!.findChapterAtTime(positionInBook);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -340,46 +332,7 @@ Uri _getUri(
|
|||
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 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 {
|
||||
extension PlaybackSessionExpandedExtension on PlaybackSessionExpanded {
|
||||
BookChapter findChapterAtTime(Duration position) {
|
||||
return chapters.firstWhere(
|
||||
(element) {
|
||||
|
|
@ -390,16 +343,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,365 +0,0 @@
|
|||
// 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:rxdart/rxdart.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/features/player/core/player_status.dart' as core;
|
||||
import 'package:vaani/features/player/providers/player_status_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 AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
|
||||
final AudioPlayer _player = AudioPlayer();
|
||||
// final List<AudioSource> _playlist = [];
|
||||
final Ref ref;
|
||||
|
||||
PlaybackSessionExpanded? _session;
|
||||
|
||||
final _currentChapterObject = BehaviorSubject<BookChapter?>.seeded(null);
|
||||
AbsAudioHandler(this.ref) {
|
||||
_setupAudioPlayer();
|
||||
}
|
||||
|
||||
void _setupAudioPlayer() {
|
||||
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 = _session?.findChapterAtTime(positionInBook);
|
||||
if (chapter != currentChapter) {
|
||||
_currentChapterObject.sink.add(chapter);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 加载有声书
|
||||
Future<void> setSourceAudiobook(
|
||||
PlaybackSessionExpanded playbackSession, {
|
||||
required Uri baseUrl,
|
||||
required String token,
|
||||
List<Uri>? downloadedUris,
|
||||
}) async {
|
||||
_session = playbackSession;
|
||||
|
||||
// 添加所有音轨
|
||||
List<AudioSource> audioSources = [];
|
||||
for (final track in playbackSession.audioTracks) {
|
||||
audioSources.add(
|
||||
AudioSource.uri(
|
||||
_getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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 seekInBook(initialPosition);
|
||||
// }
|
||||
}
|
||||
|
||||
// // 音轨切换处理
|
||||
// void _onTrackChanged(int trackIndex) {
|
||||
// if (_book == null) return;
|
||||
|
||||
// // 可以在这里处理音轨切换逻辑,比如预加载下一音轨
|
||||
// // print('切换到音轨: ${_book!.tracks[trackIndex].title}');
|
||||
// }
|
||||
|
||||
// 核心功能:跳转到指定章节
|
||||
Future<void> skipToChapter(int chapterId) async {
|
||||
if (_session == null) return;
|
||||
|
||||
final chapter = _session!.chapters.firstWhere(
|
||||
(ch) => ch.id == chapterId,
|
||||
orElse: () => throw Exception('Chapter not found'),
|
||||
);
|
||||
await seekInBook(chapter.start + offset);
|
||||
}
|
||||
|
||||
PlaybackSessionExpanded? get session => _session;
|
||||
|
||||
// 当前音轨
|
||||
AudioTrack? get currentTrack {
|
||||
if (_session == null || _player.currentIndex == null) {
|
||||
return null;
|
||||
}
|
||||
return _session!.audioTracks[_player.currentIndex!];
|
||||
}
|
||||
|
||||
// 当前章节
|
||||
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 positionInBook {
|
||||
return _player.position + (currentTrack?.startOffset ?? Duration.zero);
|
||||
}
|
||||
|
||||
Duration get bufferedPositionInBook {
|
||||
return _player.bufferedPosition +
|
||||
(currentTrack?.startOffset ?? Duration.zero);
|
||||
}
|
||||
|
||||
Duration? get chapterDuration => currentChapter?.duration;
|
||||
|
||||
Stream<PlayerState> get playerStateStream => _player.playerStateStream;
|
||||
|
||||
Stream<Duration> get positionStream => _player.positionStream;
|
||||
|
||||
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 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<BookChapter?> get chapterStream => _currentChapterObject.stream;
|
||||
|
||||
Future<void> togglePlayPause() async {
|
||||
// check if book is set
|
||||
if (_session == null) {
|
||||
return Future.value();
|
||||
}
|
||||
_player.playerState.playing ? await pause() : await play();
|
||||
}
|
||||
|
||||
// 播放控制方法
|
||||
@override
|
||||
Future<void> play() async {
|
||||
await _player.play();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pause() async {
|
||||
await _player.pause();
|
||||
}
|
||||
|
||||
// 重写上一曲/下一曲为章节导航
|
||||
@override
|
||||
Future<void> skipToNext() async {
|
||||
if (_session == null) {
|
||||
// 回退到默认行为
|
||||
return _player.seekToNext();
|
||||
}
|
||||
final chapter = currentChapter;
|
||||
if (chapter == null) {
|
||||
// 回退到默认行为
|
||||
return _player.seekToNext();
|
||||
}
|
||||
final chapterIndex = _session!.chapters.indexOf(chapter);
|
||||
if (chapterIndex < _session!.chapters.length - 1) {
|
||||
// 跳到下一章
|
||||
final nextChapter = _session!.chapters[chapterIndex + 1];
|
||||
await skipToChapter(nextChapter.id);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> skipToPrevious() async {
|
||||
final chapter = currentChapter;
|
||||
if (_session == null || chapter == null) {
|
||||
return _player.seekToPrevious();
|
||||
}
|
||||
final currentIndex = _session!.chapters.indexOf(chapter);
|
||||
if (currentIndex > 0) {
|
||||
// 跳到上一章
|
||||
final prevChapter = _session!.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);
|
||||
}
|
||||
|
||||
Future<void> setVolume(double volume) async {
|
||||
await _player.setVolume(volume);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await _player.setSpeed(speed);
|
||||
}
|
||||
|
||||
// 核心功能:跳转到全局时间位置
|
||||
Future<void> seekInBook(Duration globalPosition) async {
|
||||
if (_session == null) return;
|
||||
// 找到目标音轨和在音轨内的位置
|
||||
final track = _session!.findTrackAtTime(globalPosition);
|
||||
final index = _session!.audioTracks.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) MediaControl.skipToPrevious,
|
||||
MediaControl.rewind,
|
||||
if (_player.playing) MediaControl.pause else MediaControl.play,
|
||||
MediaControl.stop,
|
||||
MediaControl.fastForward,
|
||||
if (kIsWeb || !Platform.isAndroid) MediaControl.skipToNext,
|
||||
],
|
||||
systemActions: {
|
||||
if (kIsWeb || !Platform.isAndroid) MediaAction.skipToPrevious,
|
||||
MediaAction.rewind,
|
||||
MediaAction.seek,
|
||||
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: _player.position,
|
||||
bufferedPosition: event.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;
|
||||
},
|
||||
);
|
||||
|
||||
return uri ??
|
||||
Uri.parse('${baseUrl.toString()}${track.contentUrl}?token=$token');
|
||||
}
|
||||
|
||||
extension PlaybackSessionExpandedExtension on PlaybackSessionExpanded {
|
||||
BookChapter findChapterAtTime(Duration position) {
|
||||
return chapters.firstWhere(
|
||||
(element) {
|
||||
return element.start <= position && element.end >= position + offset;
|
||||
},
|
||||
orElse: () => chapters.first,
|
||||
);
|
||||
}
|
||||
|
||||
AudioTrack findTrackAtTime(Duration position) {
|
||||
return audioTracks.firstWhere(
|
||||
(element) {
|
||||
return element.startOffset <= position &&
|
||||
element.startOffset + element.duration >= position + offset;
|
||||
},
|
||||
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 audioTracks[index].startOffset;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
// 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);
|
||||
|
||||
// // 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();
|
||||
|
||||
// // 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,85 +0,0 @@
|
|||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
|
||||
/// will manage the playlist of items
|
||||
///
|
||||
/// you are responsible for updating the current index and sub index
|
||||
class AudiobookPlaylist {
|
||||
/// list of items in the playlist
|
||||
final List<BookExpanded> books;
|
||||
|
||||
/// current index of the item in the playlist
|
||||
int _currentIndex;
|
||||
|
||||
/// current index of the audio file in the current item
|
||||
int _subCurrentIndex;
|
||||
|
||||
// wrappers for adding and removing items
|
||||
void add(BookExpanded item) => books.add(item);
|
||||
void remove(BookExpanded item) => books.remove(item);
|
||||
void clear() {
|
||||
books.clear();
|
||||
_currentIndex = 0;
|
||||
_subCurrentIndex = 0;
|
||||
}
|
||||
|
||||
// move an item from one index to another
|
||||
void move(int from, int to) {
|
||||
final item = books.removeAt(from);
|
||||
books.insert(to, item);
|
||||
}
|
||||
|
||||
/// the book being played
|
||||
BookExpanded? get currentBook {
|
||||
if (_currentIndex >= books.length || _currentIndex < 0 || books.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return books[_currentIndex];
|
||||
}
|
||||
|
||||
/// of the book in the playlist
|
||||
int get currentIndex => _currentIndex;
|
||||
// every time current index changes, we need to update the sub index
|
||||
set currentIndex(int index) {
|
||||
// if the index is the same, do nothing
|
||||
if (_currentIndex == index) {
|
||||
return;
|
||||
}
|
||||
_currentIndex = index;
|
||||
subCurrentIndex = 0;
|
||||
}
|
||||
|
||||
/// of the audio file in the current book
|
||||
int get subCurrentIndex => _subCurrentIndex;
|
||||
|
||||
set subCurrentIndex(int index) {
|
||||
if (index < 0) {
|
||||
index = 0;
|
||||
}
|
||||
_subCurrentIndex = index;
|
||||
}
|
||||
|
||||
AudiobookPlaylist({
|
||||
this.books = const [],
|
||||
currentIndex = 0,
|
||||
subCurrentIndex = 0,
|
||||
}) : _currentIndex = currentIndex,
|
||||
_subCurrentIndex = subCurrentIndex;
|
||||
|
||||
// most important method, gets the audio file to play
|
||||
// this is needed as a library item is a list of audio files
|
||||
AudioTrack? getAudioTrack() {
|
||||
final book = currentBook;
|
||||
if (book == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (subCurrentIndex > book.tracks.length || book.tracks.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return book.tracks[subCurrentIndex];
|
||||
}
|
||||
|
||||
bool get isBookFinished => subCurrentIndex >= currentBook!.tracks.length;
|
||||
|
||||
// a method to get the next audio file and advance the sub index
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/features/player/playlist.dart';
|
||||
|
||||
part 'playlist_provider.g.dart';
|
||||
|
||||
@riverpod
|
||||
class Playlist extends _$Playlist {
|
||||
@override
|
||||
AudiobookPlaylist build() {
|
||||
return AudiobookPlaylist();
|
||||
}
|
||||
|
||||
void add(BookExpanded item) {
|
||||
state.add(item);
|
||||
ref.notifyListeners();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'playlist_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$playlistHash() => r'bed4642e4c2de829e4d0630cb5bf92bffeeb1f60';
|
||||
|
||||
/// See also [Playlist].
|
||||
@ProviderFor(Playlist)
|
||||
final playlistProvider =
|
||||
AutoDisposeNotifierProvider<Playlist, AudiobookPlaylist>.internal(
|
||||
Playlist.new,
|
||||
name: r'playlistProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$playlistHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$Playlist = AutoDisposeNotifier<AudiobookPlaylist>;
|
||||
// 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
|
||||
|
|
@ -1,71 +1,112 @@
|
|||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:audio_service/audio_service.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 shelfsdk;
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart' as core;
|
||||
import 'package:vaani/api/api_provider.dart';
|
||||
import 'package:vaani/features/player/core/audiobook_player.dart' as core;
|
||||
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.dart';
|
||||
import 'package:vaani/features/player/providers/player_status_provider.dart';
|
||||
import 'package:vaani/features/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/shared/extensions/model_conversions.dart';
|
||||
import 'package:vaani/shared/utils/helper.dart';
|
||||
|
||||
part 'audiobook_player.g.dart';
|
||||
|
||||
final _logger = Logger('AudiobookPlayerProvider');
|
||||
|
||||
const playerId = 'audiobook_player';
|
||||
|
||||
/// Simple because it doesn't rebuild when the player state changes
|
||||
/// it only rebuilds when the token changes
|
||||
@Riverpod(keepAlive: true)
|
||||
class SimpleAudiobookPlayer extends _$SimpleAudiobookPlayer {
|
||||
Future<AbsAudioHandler> audioHandlerInit(Ref ref) async {
|
||||
if (Helper.isWindows() || Helper.isLinux()) {
|
||||
// JustAudioMediaKit.ensureInitialized(windows: false);
|
||||
JustAudioMediaKit.ensureInitialized();
|
||||
}
|
||||
|
||||
final audioService = await AudioService.init(
|
||||
builder: () => AbsAudioHandler(ref),
|
||||
config: const AudioServiceConfig(
|
||||
androidNotificationChannelId: 'dr.blank.vaani.channel.audio',
|
||||
androidNotificationChannelName: 'ABSPlayback',
|
||||
androidNotificationChannelDescription:
|
||||
'Needed to control audio from lock screen',
|
||||
androidNotificationOngoing: false,
|
||||
androidStopForegroundOnPause: false,
|
||||
androidNotificationIcon: 'drawable/ic_stat_logo',
|
||||
preloadArtwork: true,
|
||||
),
|
||||
);
|
||||
return audioService;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class Player extends _$Player {
|
||||
@override
|
||||
core.AudiobookPlayer build() {
|
||||
final api = ref.watch(authenticatedApiProvider);
|
||||
final player = core.AudiobookPlayer(
|
||||
api.token!,
|
||||
api.baseUrl,
|
||||
);
|
||||
|
||||
ref.onDispose(player.dispose);
|
||||
_logger.finer('created simple player');
|
||||
|
||||
return player;
|
||||
AbsAudioHandler build() {
|
||||
return ref.watch(audioHandlerInitProvider).requireValue;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class AudiobookPlayer extends _$AudiobookPlayer {
|
||||
class Session extends _$Session {
|
||||
@override
|
||||
core.AudiobookPlayer build() {
|
||||
final player = ref.watch(simpleAudiobookPlayerProvider);
|
||||
|
||||
ref.onDispose(player.dispose);
|
||||
|
||||
// bind notify listeners to the player
|
||||
// player.playerStateStream.listen((_) {
|
||||
// ref.notifyListeners();
|
||||
// });
|
||||
|
||||
_logger.finer('created player');
|
||||
|
||||
return player;
|
||||
core.PlaybackSessionExpanded? build() {
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await state.setSpeed(speed);
|
||||
ref.notifyListeners();
|
||||
}
|
||||
Future<void> load(String id, String? episodeId) async {
|
||||
final audioService = ref.read(playerProvider);
|
||||
await audioService.pause();
|
||||
ref.read(playerStatusProvider.notifier).setLoading(id);
|
||||
final api = ref.read(authenticatedApiProvider);
|
||||
final playBack = await ref.watch(playBackSessionProvider(id).future);
|
||||
if (playBack == null) {
|
||||
return;
|
||||
}
|
||||
state = playBack.asExpanded;
|
||||
final downloadManager = ref.read(simpleDownloadManagerProvider);
|
||||
final libItem =
|
||||
await ref.read(libraryItemProvider(state!.libraryItemId).future);
|
||||
final downloadedUris = await downloadManager.getDownloadedFilesUri(libItem);
|
||||
|
||||
Future<void> setSourceAudiobook({
|
||||
required shelfsdk.BookExpanded book,
|
||||
shelfsdk.MediaProgress? userMediaProgress,
|
||||
}) async {
|
||||
ref.notifyListeners();
|
||||
var bookPlayerSettings =
|
||||
ref.read(bookSettingsProvider(state!.libraryItemId)).playerSettings;
|
||||
var appPlayerSettings = ref.read(appSettingsProvider).playerSettings;
|
||||
|
||||
var configurePlayerForEveryBook =
|
||||
appPlayerSettings.configurePlayerForEveryBook;
|
||||
|
||||
await Future.wait([
|
||||
audioService.setSourceAudiobook(
|
||||
state!.asExpanded,
|
||||
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,
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@riverpod
|
||||
bool isPlayerPlaying(
|
||||
Ref ref,
|
||||
) {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
print("playing: ${player.playing}");
|
||||
return player.playing;
|
||||
class PlaybackSyncError implements Exception {
|
||||
String message;
|
||||
|
||||
PlaybackSyncError([this.message = 'Error syncing playback']);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'PlaybackSyncError: $message';
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,58 +6,51 @@ part of 'audiobook_player.dart';
|
|||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$isPlayerPlayingHash() => r'b81fa9cfb51c88c8d9e8f5c1f4f6a12d9e5a0cc1';
|
||||
String _$audioHandlerInitHash() => r'6e4662a45c1c6e84aa16436f71ffcfecc3d4bdab';
|
||||
|
||||
/// See also [isPlayerPlaying].
|
||||
@ProviderFor(isPlayerPlaying)
|
||||
final isPlayerPlayingProvider = AutoDisposeProvider<bool>.internal(
|
||||
isPlayerPlaying,
|
||||
name: r'isPlayerPlayingProvider',
|
||||
/// See also [audioHandlerInit].
|
||||
@ProviderFor(audioHandlerInit)
|
||||
final audioHandlerInitProvider = FutureProvider<AbsAudioHandler>.internal(
|
||||
audioHandlerInit,
|
||||
name: r'audioHandlerInitProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$isPlayerPlayingHash,
|
||||
: _$audioHandlerInitHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef IsPlayerPlayingRef = AutoDisposeProviderRef<bool>;
|
||||
String _$simpleAudiobookPlayerHash() =>
|
||||
r'5e94bbff4314adceb5affa704fc4d079d4016afa';
|
||||
typedef AudioHandlerInitRef = FutureProviderRef<AbsAudioHandler>;
|
||||
String _$playerHash() => r'9599b094cdd9eca614c27ec5bdf2d5259d20ac5f';
|
||||
|
||||
/// Simple because it doesn't rebuild when the player state changes
|
||||
/// it only rebuilds when the token changes
|
||||
///
|
||||
/// Copied from [SimpleAudiobookPlayer].
|
||||
@ProviderFor(SimpleAudiobookPlayer)
|
||||
final simpleAudiobookPlayerProvider =
|
||||
NotifierProvider<SimpleAudiobookPlayer, core.AudiobookPlayer>.internal(
|
||||
SimpleAudiobookPlayer.new,
|
||||
name: r'simpleAudiobookPlayerProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$simpleAudiobookPlayerHash,
|
||||
/// 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 _$SimpleAudiobookPlayer = Notifier<core.AudiobookPlayer>;
|
||||
String _$audiobookPlayerHash() => r'04448247e79c5d60b9fd6f98eeeb865f1e8d0ff8';
|
||||
typedef _$Player = Notifier<AbsAudioHandler>;
|
||||
String _$sessionHash() => r'c171809249c3021dc445dc1ba90fe8626a3d3b54';
|
||||
|
||||
/// See also [AudiobookPlayer].
|
||||
@ProviderFor(AudiobookPlayer)
|
||||
final audiobookPlayerProvider =
|
||||
NotifierProvider<AudiobookPlayer, core.AudiobookPlayer>.internal(
|
||||
AudiobookPlayer.new,
|
||||
name: r'audiobookPlayerProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$audiobookPlayerHash,
|
||||
/// See also [Session].
|
||||
@ProviderFor(Session)
|
||||
final sessionProvider =
|
||||
NotifierProvider<Session, core.PlaybackSessionExpanded?>.internal(
|
||||
Session.new,
|
||||
name: r'sessionProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$sessionHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$AudiobookPlayer = Notifier<core.AudiobookPlayer>;
|
||||
typedef _$Session = Notifier<core.PlaybackSessionExpanded?>;
|
||||
// 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
|
||||
|
|
|
|||
|
|
@ -1,46 +1,40 @@
|
|||
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';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart' as core;
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
import 'package:vaani/shared/extensions/model_conversions.dart';
|
||||
|
||||
part 'currently_playing_provider.g.dart';
|
||||
|
||||
final _logger = Logger('CurrentlyPlayingProvider');
|
||||
|
||||
@riverpod
|
||||
BookExpanded? currentlyPlayingBook(Ref ref) {
|
||||
try {
|
||||
final book = ref.watch(simpleAudiobookPlayerProvider.select((v) => v.book));
|
||||
return book;
|
||||
} catch (e) {
|
||||
_logger.warning('Error getting currently playing book: $e');
|
||||
return null;
|
||||
class CurrentChapter extends _$CurrentChapter {
|
||||
@override
|
||||
core.BookChapter? build() {
|
||||
final player = ref.watch(playerProvider);
|
||||
player.chapterStream.distinct().listen((chapter) {
|
||||
update(chapter);
|
||||
});
|
||||
return player.currentChapter;
|
||||
}
|
||||
|
||||
void update(core.BookChapter? chapter) {
|
||||
if (state != chapter) {
|
||||
state = chapter;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// provided the current chapter of the book being played
|
||||
@riverpod
|
||||
BookChapter? currentPlayingChapter(Ref ref) {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
player.slowPositionStreamInBook.listen((_) {
|
||||
ref.invalidateSelf();
|
||||
});
|
||||
|
||||
return player.currentChapter;
|
||||
List<core.BookChapter> currentChapters(Ref ref) {
|
||||
final session = ref.watch(sessionProvider);
|
||||
if (session == null) {
|
||||
return [];
|
||||
}
|
||||
final currentChapter = ref.watch(currentChapterProvider);
|
||||
if (currentChapter == null) {
|
||||
return [];
|
||||
}
|
||||
final index = session.chapters.indexOf(currentChapter);
|
||||
final total = session.chapters.length;
|
||||
return session.chapters
|
||||
.sublist(index - 3, (total - 3) <= (index + 17) ? total : index + 17);
|
||||
}
|
||||
|
||||
/// provides the book metadata of the currently playing book
|
||||
@riverpod
|
||||
BookMetadataExpanded? currentBookMetadata(Ref ref) {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
if (player.book == null) return null;
|
||||
return player.book!.metadata.asBookMetadataExpanded;
|
||||
}
|
||||
|
||||
// /// volume of the player [0, 1]
|
||||
// @riverpod
|
||||
// double currentVolume(CurrentVolumeRef ref) {
|
||||
// return 1;
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -6,66 +6,39 @@ part of 'currently_playing_provider.dart';
|
|||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$currentlyPlayingBookHash() =>
|
||||
r'f2c47028340d253be9440dc29f835328ff30c0e6';
|
||||
String _$currentChaptersHash() => r'f2cc6ec31b5a3a9471775b1c96b2bfc3a91f1c90';
|
||||
|
||||
/// See also [currentlyPlayingBook].
|
||||
@ProviderFor(currentlyPlayingBook)
|
||||
final currentlyPlayingBookProvider =
|
||||
AutoDisposeProvider<BookExpanded?>.internal(
|
||||
currentlyPlayingBook,
|
||||
name: r'currentlyPlayingBookProvider',
|
||||
/// See also [currentChapters].
|
||||
@ProviderFor(currentChapters)
|
||||
final currentChaptersProvider =
|
||||
AutoDisposeProvider<List<core.BookChapter>>.internal(
|
||||
currentChapters,
|
||||
name: r'currentChaptersProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$currentlyPlayingBookHash,
|
||||
: _$currentChaptersHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef CurrentlyPlayingBookRef = AutoDisposeProviderRef<BookExpanded?>;
|
||||
String _$currentPlayingChapterHash() =>
|
||||
r'4a64157089279c71279ccfdbcfc7b32543ecc88c';
|
||||
typedef CurrentChaptersRef = AutoDisposeProviderRef<List<core.BookChapter>>;
|
||||
String _$currentChapterHash() => r'f5f6d9e49cb7e455d032f7370f364d9ce30b8eb1';
|
||||
|
||||
/// provided the current chapter of the book being played
|
||||
///
|
||||
/// Copied from [currentPlayingChapter].
|
||||
@ProviderFor(currentPlayingChapter)
|
||||
final currentPlayingChapterProvider =
|
||||
AutoDisposeProvider<BookChapter?>.internal(
|
||||
currentPlayingChapter,
|
||||
name: r'currentPlayingChapterProvider',
|
||||
/// See also [CurrentChapter].
|
||||
@ProviderFor(CurrentChapter)
|
||||
final currentChapterProvider =
|
||||
AutoDisposeNotifierProvider<CurrentChapter, core.BookChapter?>.internal(
|
||||
CurrentChapter.new,
|
||||
name: r'currentChapterProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$currentPlayingChapterHash,
|
||||
: _$currentChapterHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef CurrentPlayingChapterRef = AutoDisposeProviderRef<BookChapter?>;
|
||||
String _$currentBookMetadataHash() =>
|
||||
r'f537ef4ef19280bc952de658ecf6520c535ae344';
|
||||
|
||||
/// provides the book metadata of the currently playing book
|
||||
///
|
||||
/// Copied from [currentBookMetadata].
|
||||
@ProviderFor(currentBookMetadata)
|
||||
final currentBookMetadataProvider =
|
||||
AutoDisposeProvider<BookMetadataExpanded?>.internal(
|
||||
currentBookMetadata,
|
||||
name: r'currentBookMetadataProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$currentBookMetadataHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef CurrentBookMetadataRef = AutoDisposeProviderRef<BookMetadataExpanded?>;
|
||||
typedef _$CurrentChapter = AutoDisposeNotifier<core.BookChapter?>;
|
||||
// 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
|
||||
|
|
|
|||
|
|
@ -1,80 +0,0 @@
|
|||
// this provider is used to manage the player form state
|
||||
// it will inform about the percentage of the player expanded
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
// import 'package:miniplayer/miniplayer.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
|
||||
part 'player_form.g.dart';
|
||||
|
||||
/// The height of the player when it is minimized
|
||||
const double playerMinHeight = 70;
|
||||
// const miniplayerPercentageDeclaration = 0.2;
|
||||
|
||||
extension on Ref {
|
||||
// We can move the previous logic to a Ref extension.
|
||||
// This enables reusing the logic between providers
|
||||
T disposeAndListenChangeNotifier<T extends ChangeNotifier>(T notifier) {
|
||||
onDispose(notifier.dispose);
|
||||
notifier.addListener(notifyListeners);
|
||||
// We return the notifier to ease the usage a bit
|
||||
return notifier;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Raw<ValueNotifier<double>> playerExpandProgressNotifier(
|
||||
Ref ref,
|
||||
) {
|
||||
final ValueNotifier<double> playerExpandProgress =
|
||||
ValueNotifier(playerMinHeight);
|
||||
|
||||
return ref.disposeAndListenChangeNotifier(playerExpandProgress);
|
||||
}
|
||||
|
||||
// @Riverpod(keepAlive: true)
|
||||
// Raw<ValueNotifier<double>> dragDownPercentageNotifier(
|
||||
// DragDownPercentageNotifierRef ref,
|
||||
// ) {
|
||||
// final ValueNotifier<double> notifier = ValueNotifier(0);
|
||||
|
||||
// return ref.disposeAndListenChangeNotifier(notifier);
|
||||
// }
|
||||
|
||||
// a provider that will listen to the playerExpandProgressNotifier and return the percentage of the player expanded
|
||||
@Riverpod(keepAlive: true)
|
||||
double playerHeight(
|
||||
Ref ref,
|
||||
) {
|
||||
final playerExpandProgress = ref.watch(playerExpandProgressNotifierProvider);
|
||||
|
||||
// on change of the playerExpandProgress invalidate
|
||||
playerExpandProgress.addListener(() {
|
||||
ref.invalidateSelf();
|
||||
});
|
||||
|
||||
// listen to the playerExpandProgressNotifier and return the value
|
||||
return playerExpandProgress.value;
|
||||
}
|
||||
|
||||
// final audioBookMiniplayerController = MiniplayerController();
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
bool isPlayerActive(
|
||||
Ref ref,
|
||||
) {
|
||||
try {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
if (player.book != null) {
|
||||
return true;
|
||||
} else {
|
||||
final playerHeight = ref.watch(playerHeightProvider);
|
||||
return playerHeight < playerMinHeight;
|
||||
}
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'player_form.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$playerExpandProgressNotifierHash() =>
|
||||
r'1ac7172d90a070f96222286edd1a176be197f378';
|
||||
|
||||
/// See also [playerExpandProgressNotifier].
|
||||
@ProviderFor(playerExpandProgressNotifier)
|
||||
final playerExpandProgressNotifierProvider =
|
||||
Provider<Raw<ValueNotifier<double>>>.internal(
|
||||
playerExpandProgressNotifier,
|
||||
name: r'playerExpandProgressNotifierProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$playerExpandProgressNotifierHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef PlayerExpandProgressNotifierRef
|
||||
= ProviderRef<Raw<ValueNotifier<double>>>;
|
||||
String _$playerHeightHash() => r'3f031eaffdffbb2c6ddf7eb1aba31bf1619260fc';
|
||||
|
||||
/// See also [playerHeight].
|
||||
@ProviderFor(playerHeight)
|
||||
final playerHeightProvider = Provider<double>.internal(
|
||||
playerHeight,
|
||||
name: r'playerHeightProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$playerHeightHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef PlayerHeightRef = ProviderRef<double>;
|
||||
String _$isPlayerActiveHash() => r'2c7ca125423126fb5f0ef218d37bc8fe0ca9ec98';
|
||||
|
||||
/// See also [isPlayerActive].
|
||||
@ProviderFor(isPlayerActive)
|
||||
final isPlayerActiveProvider = Provider<bool>.internal(
|
||||
isPlayerActive,
|
||||
name: r'isPlayerActiveProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$isPlayerActiveHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef IsPlayerActiveRef = ProviderRef<bool>;
|
||||
// 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
|
||||
|
|
@ -1 +0,0 @@
|
|||
|
||||
|
|
@ -1,188 +0,0 @@
|
|||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
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/playback_reporting/core/playback_reporter_session.dart'
|
||||
as core;
|
||||
import 'package:vaani/features/player/core/audiobook_player_session.dart';
|
||||
import 'package:vaani/features/player/providers/player_status_provider.dart';
|
||||
import 'package:vaani/globals.dart';
|
||||
import 'package:vaani/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/shared/extensions/obfuscation.dart';
|
||||
import 'package:vaani/shared/utils/utils.dart';
|
||||
|
||||
part 'session_provider.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<AbsAudioHandler> audioHandlerInit(Ref ref) async {
|
||||
if (Utils.isWindows() || Utils.isLinux()) {
|
||||
// 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,
|
||||
),
|
||||
);
|
||||
return audioService;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class Player extends _$Player {
|
||||
@override
|
||||
AbsAudioHandler build() {
|
||||
return ref.watch(audioHandlerInitProvider).requireValue;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class Session extends _$Session {
|
||||
@override
|
||||
core.PlaybackSessionExpanded? build() {
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> load(String id, String? episodeId) async {
|
||||
final audioService = ref.read(playerProvider);
|
||||
await audioService.pause();
|
||||
ref.read(playerStatusProvider.notifier).setLoading(id);
|
||||
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;
|
||||
state = playBack;
|
||||
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,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
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 CurrentChapter extends _$CurrentChapter {
|
||||
@override
|
||||
core.BookChapter? build() {
|
||||
final player = ref.watch(playerProvider);
|
||||
player.chapterStream.distinct().listen((chapter) {
|
||||
update(chapter);
|
||||
});
|
||||
return player.currentChapter;
|
||||
}
|
||||
|
||||
void update(core.BookChapter? chapter) {
|
||||
if (state != chapter) {
|
||||
state = chapter;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class PlaybackReporter extends _$PlaybackReporter {
|
||||
@override
|
||||
Future<core.PlaybackReporter?> build() async {
|
||||
final session = ref.watch(sessionProvider);
|
||||
if (session == null) {
|
||||
return null;
|
||||
}
|
||||
final playerSettings = ref.watch(appSettingsProvider).playerSettings;
|
||||
final player = ref.watch(playerProvider);
|
||||
final api = ref.watch(authenticatedApiProvider);
|
||||
|
||||
final reporter = core.PlaybackReporter(
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'session_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$audioHandlerInitHash() => r'c54f17757807f8bc14daff5095c34eb88ff2037b';
|
||||
|
||||
/// 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'9599b094cdd9eca614c27ec5bdf2d5259d20ac5f';
|
||||
|
||||
/// 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 _$sessionHash() => r'ce9405cc0b8247014924a005fa60fbc3bf92d5c6';
|
||||
|
||||
/// See also [Session].
|
||||
@ProviderFor(Session)
|
||||
final sessionProvider =
|
||||
NotifierProvider<Session, core.PlaybackSessionExpanded?>.internal(
|
||||
Session.new,
|
||||
name: r'sessionProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$sessionHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$Session = Notifier<core.PlaybackSessionExpanded?>;
|
||||
String _$currentChapterHash() => r'0be02fbc4f65b30da4ce18964ee457a18c4d1073';
|
||||
|
||||
/// See also [CurrentChapter].
|
||||
@ProviderFor(CurrentChapter)
|
||||
final currentChapterProvider =
|
||||
NotifierProvider<CurrentChapter, core.BookChapter?>.internal(
|
||||
CurrentChapter.new,
|
||||
name: r'currentChapterProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$currentChapterHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$CurrentChapter = Notifier<core.BookChapter?>;
|
||||
String _$playbackReporterHash() => r'b9a2197a12e83f9760bd61ae2a1ad8dff82042e9';
|
||||
|
||||
/// See also [PlaybackReporter].
|
||||
@ProviderFor(PlaybackReporter)
|
||||
final playbackReporterProvider =
|
||||
AsyncNotifierProvider<PlaybackReporter, core.PlaybackReporter?>.internal(
|
||||
PlaybackReporter.new,
|
||||
name: r'playbackReporterProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$playbackReporterHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$PlaybackReporter = AsyncNotifier<core.PlaybackReporter?>;
|
||||
// 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
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/features/player/providers/player_form.dart';
|
||||
import 'package:vaani/features/player/providers/player_status_provider.dart';
|
||||
import 'package:vaani/globals.dart' show playerMinHeight;
|
||||
|
||||
class MiniPlayerBottomPadding extends HookConsumerWidget {
|
||||
const MiniPlayerBottomPadding({super.key});
|
||||
|
|
@ -8,7 +9,7 @@ class MiniPlayerBottomPadding extends HookConsumerWidget {
|
|||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return AnimatedSize(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
child: ref.watch(isPlayerActiveProvider)
|
||||
child: ref.watch(playerStatusProvider).isPlaying()
|
||||
? const SizedBox(height: playerMinHeight + 8)
|
||||
: const SizedBox.shrink(),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,15 +1,14 @@
|
|||
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/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.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/view/widgets/player_player_pause_button.dart';
|
||||
import 'package:vaani/features/player/view/widgets/player_progress_bar.dart';
|
||||
import 'package:vaani/features/player/view/widgets/player_skip_chapter_start_end.dart';
|
||||
import 'package:vaani/features/skip_start_end/view/skip_start_end_button.dart';
|
||||
import 'package:vaani/features/sleep_timer/view/sleep_timer_button.dart';
|
||||
import 'package:vaani/shared/widgets/not_implemented.dart';
|
||||
import 'package:vaani/shared/widgets/shelves/book_shelf.dart';
|
||||
|
||||
import 'widgets/audiobook_player_seek_button.dart';
|
||||
|
|
@ -40,172 +39,162 @@ class PlayerExpanded extends HookConsumerWidget {
|
|||
final availWidth = MediaQuery.of(context).size.width;
|
||||
// the image width when the player is expanded
|
||||
final imageSize = min(playerMaxHeight * 0.5, availWidth * 0.9);
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
iconSize: 30,
|
||||
icon: const Icon(Icons.keyboard_arrow_down),
|
||||
onPressed: () => context.pop(),
|
||||
return Column(
|
||||
children: [
|
||||
// sized box for system status bar; not needed as not full screen
|
||||
SizedBox(
|
||||
height: MediaQuery.of(context).padding.top,
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.cast),
|
||||
onPressed: () {
|
||||
showNotImplementedToast(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// sized box for system status bar; not needed as not full screen
|
||||
SizedBox(
|
||||
height: MediaQuery.of(context).padding.top,
|
||||
),
|
||||
|
||||
// the image
|
||||
Padding(
|
||||
padding: EdgeInsets.only(top: AppElementSizes.paddingLarge),
|
||||
child: Align(
|
||||
alignment: Alignment.center,
|
||||
// add a shadow to the image elevation hovering effect
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.primary
|
||||
.withValues(alpha: 0.1),
|
||||
blurRadius: 32,
|
||||
spreadRadius: 8,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: SizedBox(
|
||||
height: imageSize,
|
||||
child: InkWell(
|
||||
onTap: () {},
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppElementSizes.borderRadiusRegular,
|
||||
),
|
||||
child: BookCoverWidget(),
|
||||
),
|
||||
// the image
|
||||
Padding(
|
||||
padding: EdgeInsets.only(top: AppElementSizes.paddingLarge),
|
||||
child: Align(
|
||||
alignment: Alignment.center,
|
||||
// add a shadow to the image elevation hovering effect
|
||||
child: PlayerExpandedImage(imageSize),
|
||||
),
|
||||
),
|
||||
|
||||
// the chapter title
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(top: AppElementSizes.paddingRegular),
|
||||
child: currentChapter == null
|
||||
? const SizedBox()
|
||||
: Text(
|
||||
currentChapter.title,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// the book name and author
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(bottom: AppElementSizes.paddingRegular),
|
||||
child: Text(
|
||||
[
|
||||
session.displayTitle,
|
||||
session.displayAuthor,
|
||||
].join(' - '),
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurface
|
||||
.withValues(alpha: 0.7),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// the chapter title
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(top: AppElementSizes.paddingRegular),
|
||||
child: currentChapter == null
|
||||
? const SizedBox()
|
||||
: Text(
|
||||
currentChapter.title,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// the book name and author
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(bottom: AppElementSizes.paddingRegular),
|
||||
child: Text(
|
||||
[
|
||||
session.displayTitle,
|
||||
session.displayAuthor,
|
||||
].join(' - '),
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurface
|
||||
.withValues(alpha: 0.7),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// the progress bar
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
width: imageSize,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(
|
||||
left: AppElementSizes.paddingRegular,
|
||||
right: AppElementSizes.paddingRegular,
|
||||
),
|
||||
child: const AudiobookChapterProgressBar(),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(
|
||||
// the progress bar
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
width: imageSize,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(
|
||||
left: AppElementSizes.paddingRegular,
|
||||
right: AppElementSizes.paddingRegular,
|
||||
),
|
||||
child: const AudiobookProgressBar(),
|
||||
child: const AudiobookChapterProgressBar(),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// the chapter skip buttons, seek 30 seconds back and forward, and play/pause button
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: SizedBox(
|
||||
width: imageSize,
|
||||
height: AppElementSizes.iconSizeRegular,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// previous chapter
|
||||
const AudiobookPlayerSeekChapterButton(isForward: false),
|
||||
// buttonSkipBackwards
|
||||
const AudiobookPlayerSeekButton(isForward: false),
|
||||
AudiobookPlayerPlayPauseButton(),
|
||||
// buttonSkipForwards
|
||||
const AudiobookPlayerSeekButton(isForward: true),
|
||||
// next chapter
|
||||
const AudiobookPlayerSeekChapterButton(isForward: true),
|
||||
],
|
||||
),
|
||||
SizedBox(
|
||||
width: imageSize,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(
|
||||
left: AppElementSizes.paddingRegular,
|
||||
right: AppElementSizes.paddingRegular,
|
||||
),
|
||||
child: const AudiobookProgressBar(),
|
||||
),
|
||||
),
|
||||
|
||||
// the chapter skip buttons, seek 30 seconds back and forward, and play/pause button
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: SizedBox(
|
||||
width: imageSize,
|
||||
height: AppElementSizes.iconSizeRegular,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// previous chapter
|
||||
const AudiobookPlayerSeekChapterButton(isForward: false),
|
||||
// buttonSkipBackwards
|
||||
const AudiobookPlayerSeekButton(isForward: false),
|
||||
AudiobookPlayerPlayPauseButton(),
|
||||
// buttonSkipForwards
|
||||
const AudiobookPlayerSeekButton(isForward: true),
|
||||
// next chapter
|
||||
const AudiobookPlayerSeekChapterButton(isForward: true),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// speed control, sleep timer, chapter list, and settings
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
width: imageSize,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
// speed control
|
||||
const PlayerSpeedAdjustButton(),
|
||||
const Spacer(),
|
||||
// sleep timer
|
||||
const SleepTimerButton(),
|
||||
const Spacer(),
|
||||
// chapter list
|
||||
const ChapterSelectionButton(),
|
||||
const Spacer(),
|
||||
// 跳过片头片尾
|
||||
SkipChapterStartEndButton(),
|
||||
],
|
||||
),
|
||||
// speed control, sleep timer, chapter list, and settings
|
||||
Expanded(
|
||||
child: SizedBox(
|
||||
width: imageSize,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
// speed control
|
||||
const PlayerSpeedAdjustButton(),
|
||||
const Spacer(),
|
||||
// sleep timer
|
||||
const SleepTimerButton(),
|
||||
const Spacer(),
|
||||
// chapter list
|
||||
const ChapterSelectionButton(),
|
||||
const Spacer(),
|
||||
// 跳过片头片尾
|
||||
SkipChapterStartEndButton(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PlayerExpandedImage extends StatelessWidget {
|
||||
final double imageSize;
|
||||
|
||||
const PlayerExpandedImage(this.imageSize, {super.key});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.1),
|
||||
blurRadius: 32,
|
||||
spreadRadius: 8,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: SizedBox(
|
||||
height: imageSize,
|
||||
child: InkWell(
|
||||
onTap: () {},
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppElementSizes.borderRadiusRegular,
|
||||
),
|
||||
child: BookCoverWidget(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
174
lib/features/player/view/player_expanded_desktop.dart
Normal file
174
lib/features/player/view/player_expanded_desktop.dart
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.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/view/player_expanded.dart'
|
||||
show PlayerExpandedImage;
|
||||
import 'package:vaani/features/player/view/player_minimized.dart';
|
||||
import 'package:vaani/features/player/view/widgets/audiobook_player_seek_button.dart';
|
||||
import 'package:vaani/features/player/view/widgets/audiobook_player_seek_chapter_button.dart';
|
||||
import 'package:vaani/features/player/view/widgets/player_player_pause_button.dart';
|
||||
import 'package:vaani/features/player/view/widgets/player_speed_adjust_button.dart';
|
||||
import 'package:vaani/features/skip_start_end/view/skip_start_end_button.dart';
|
||||
import 'package:vaani/features/sleep_timer/view/sleep_timer_button.dart';
|
||||
import 'package:vaani/globals.dart';
|
||||
import 'package:vaani/shared/extensions/chapter.dart';
|
||||
import 'package:vaani/shared/extensions/duration_format.dart';
|
||||
|
||||
var pendingPlayerModals = 0;
|
||||
|
||||
class PlayerExpandedDesktop extends HookConsumerWidget {
|
||||
const PlayerExpandedDesktop({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final session = ref.watch(sessionProvider);
|
||||
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 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);
|
||||
|
||||
return Stack(
|
||||
alignment: Alignment.bottomCenter,
|
||||
children: [
|
||||
Scaffold(
|
||||
body: Padding(
|
||||
padding: EdgeInsets.only(
|
||||
top: AppElementSizes.paddingLarge,
|
||||
bottom: playerMinHeight + 40,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 45,
|
||||
child: Column(
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.topCenter,
|
||||
// add a shadow to the image elevation hovering effect
|
||||
child: PlayerExpandedImage(imageSize),
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// previous chapter
|
||||
const AudiobookPlayerSeekChapterButton(
|
||||
isForward: false),
|
||||
// buttonSkipBackwards
|
||||
const AudiobookPlayerSeekButton(isForward: false),
|
||||
AudiobookPlayerPlayPauseButton(),
|
||||
// buttonSkipForwards
|
||||
const AudiobookPlayerSeekButton(isForward: true),
|
||||
// next chapter
|
||||
const AudiobookPlayerSeekChapterButton(
|
||||
isForward: true),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
// speed control
|
||||
const PlayerSpeedAdjustButton(),
|
||||
const Spacer(),
|
||||
// sleep timer
|
||||
const SleepTimerButton(),
|
||||
const Spacer(),
|
||||
// 跳过片头片尾
|
||||
SkipChapterStartEndButton(),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 65,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
currentChapter == null
|
||||
? SizedBox.shrink()
|
||||
: Text(
|
||||
currentChapter.title,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
Expanded(
|
||||
child: ChapterSelection(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Hero(tag: 'player_hero', child: const PlayerMinimized()),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ChapterSelection extends HookConsumerWidget {
|
||||
const ChapterSelection({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final currentChapter = ref.watch(currentChapterProvider);
|
||||
if (currentChapter == null) {
|
||||
return SizedBox.shrink();
|
||||
}
|
||||
|
||||
final currentChapters = ref.watch(currentChaptersProvider);
|
||||
final currentChapterIndex = currentChapters.indexOf(currentChapter);
|
||||
final theme = Theme.of(context);
|
||||
return Scrollbar(
|
||||
child: ListView.builder(
|
||||
itemCount: currentChapters.length,
|
||||
itemBuilder: (context, index) {
|
||||
final chapter = currentChapters[index];
|
||||
final isCurrent = currentChapterIndex == index;
|
||||
final isPlayed = index < currentChapterIndex;
|
||||
return ListTile(
|
||||
autofocus: isCurrent,
|
||||
iconColor: isPlayed && !isCurrent ? theme.disabledColor : null,
|
||||
title: Text(
|
||||
chapter.title,
|
||||
style: isPlayed && !isCurrent
|
||||
? TextStyle(color: theme.disabledColor)
|
||||
: null,
|
||||
),
|
||||
subtitle: Text(
|
||||
'(${chapter.duration.smartBinaryFormat})',
|
||||
style: isPlayed && !isCurrent
|
||||
? TextStyle(color: theme.disabledColor)
|
||||
: null,
|
||||
),
|
||||
// trailing: isCurrent
|
||||
// ? const PlayingIndicatorIcon()
|
||||
// : const Icon(Icons.play_arrow),
|
||||
selected: isCurrent,
|
||||
// key: isCurrent ? chapterKey : null,
|
||||
onTap: () {
|
||||
ref.read(playerProvider).skipToChapter(chapter.id);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -4,7 +4,8 @@ import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
|
|||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.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/view/widgets/player_player_pause_button.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
import 'package:vaani/shared/widgets/shelves/book_shelf.dart';
|
||||
|
|
@ -28,7 +29,7 @@ class PlayerMinimized extends HookConsumerWidget {
|
|||
// image
|
||||
Padding(
|
||||
padding: EdgeInsets.all(AppElementSizes.paddingSmall),
|
||||
child: InkWell(
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
// navigate to item page
|
||||
context.pushNamed(
|
||||
|
|
@ -114,7 +115,13 @@ class PlayerMinimizedFramework extends HookConsumerWidget {
|
|||
final progress =
|
||||
useStream(player.positionStreamInChapter, initialData: Duration.zero);
|
||||
return GestureDetector(
|
||||
onTap: () => context.pushNamed(Routes.player.name),
|
||||
onTap: () {
|
||||
if (GoRouterState.of(context).topRoute?.name != Routes.player.name) {
|
||||
context.pushNamed(Routes.player.name);
|
||||
} else {
|
||||
context.pop();
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
height: playerMinimizedHeight,
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
|
|
|
|||
|
|
@ -1,293 +0,0 @@
|
|||
// import 'package:flutter/material.dart';
|
||||
// import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
// import 'package:miniplayer/miniplayer.dart';
|
||||
// import 'package:vaani/constants/sizes.dart';
|
||||
// import 'package:vaani/features/player/providers/currently_playing_provider.dart';
|
||||
// import 'package:vaani/features/player/providers/player_form.dart';
|
||||
// import 'package:vaani/features/player/view/audiobook_player.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';
|
||||
// import 'package:vaani/features/sleep_timer/view/sleep_timer_button.dart';
|
||||
// import 'package:vaani/shared/extensions/inverse_lerp.dart';
|
||||
// import 'package:vaani/shared/widgets/not_implemented.dart';
|
||||
|
||||
// import 'widgets/audiobook_player_seek_button.dart';
|
||||
// import 'widgets/audiobook_player_seek_chapter_button.dart';
|
||||
// import 'widgets/chapter_selection_button.dart';
|
||||
// import 'widgets/player_speed_adjust_button.dart';
|
||||
|
||||
// var pendingPlayerModals = 0;
|
||||
|
||||
// class PlayerWhenExpanded extends HookConsumerWidget {
|
||||
// const PlayerWhenExpanded({
|
||||
// super.key,
|
||||
// required this.imageSize,
|
||||
// required this.img,
|
||||
// required this.percentageExpandedPlayer,
|
||||
// required this.playPauseController,
|
||||
// });
|
||||
|
||||
// /// padding values control the position of the image
|
||||
// final double imageSize;
|
||||
// final Widget img;
|
||||
// final double percentageExpandedPlayer;
|
||||
// final AnimationController playPauseController;
|
||||
|
||||
// @override
|
||||
// Widget build(BuildContext context, WidgetRef ref) {
|
||||
// /// 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%
|
||||
// const lateStart = 0.4;
|
||||
// const earlyEnd = 1;
|
||||
// final earlyPercentage = percentageExpandedPlayer
|
||||
// .inverseLerp(
|
||||
// lateStart,
|
||||
// earlyEnd,
|
||||
// )
|
||||
// .clamp(0.0, 1.0);
|
||||
// final currentChapter = ref.watch(currentPlayingChapterProvider);
|
||||
// final currentBookMetadata = ref.watch(currentBookMetadataProvider);
|
||||
|
||||
// return Column(
|
||||
// children: [
|
||||
// // sized box for system status bar; not needed as not full screen
|
||||
// SizedBox(
|
||||
// height: MediaQuery.of(context).padding.top * earlyPercentage,
|
||||
// ),
|
||||
|
||||
// // a row with a down arrow to minimize the player, a pill shaped container to drag the player, and a cast button
|
||||
// ConstrainedBox(
|
||||
// constraints: BoxConstraints(
|
||||
// maxHeight: 100 * earlyPercentage,
|
||||
// ),
|
||||
// child: Opacity(
|
||||
// opacity: earlyPercentage,
|
||||
// child: Padding(
|
||||
// padding: EdgeInsets.only(top: 8.0 * earlyPercentage),
|
||||
// child: Row(
|
||||
// crossAxisAlignment: CrossAxisAlignment.center,
|
||||
// mainAxisSize: MainAxisSize.max,
|
||||
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
// children: [
|
||||
// // the down arrow
|
||||
// IconButton(
|
||||
// iconSize: 30,
|
||||
// icon: const Icon(Icons.keyboard_arrow_down),
|
||||
// onPressed: () {
|
||||
// // minimize the player
|
||||
// audioBookMiniplayerController.animateToHeight(
|
||||
// state: PanelState.MIN,
|
||||
// );
|
||||
// },
|
||||
// ),
|
||||
|
||||
// // the cast button
|
||||
// IconButton(
|
||||
// icon: const Icon(Icons.cast),
|
||||
// onPressed: () {
|
||||
// showNotImplementedToast(context);
|
||||
// },
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// // the image
|
||||
// Padding(
|
||||
// padding: EdgeInsets.only(
|
||||
// top: AppElementSizes.paddingLarge * earlyPercentage,
|
||||
// ),
|
||||
// child: Align(
|
||||
// alignment: Alignment.center,
|
||||
// // add a shadow to the image elevation hovering effect
|
||||
// child: Container(
|
||||
// decoration: BoxDecoration(
|
||||
// boxShadow: [
|
||||
// BoxShadow(
|
||||
// color: Theme.of(context)
|
||||
// .colorScheme
|
||||
// .primary
|
||||
// .withValues(alpha: 0.1),
|
||||
// blurRadius: 32 * earlyPercentage,
|
||||
// spreadRadius: 8 * earlyPercentage,
|
||||
// // offset: Offset(0, 16 * earlyPercentage),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// child: SizedBox(
|
||||
// height: imageSize,
|
||||
// child: InkWell(
|
||||
// onTap: () {},
|
||||
// child: ClipRRect(
|
||||
// borderRadius: BorderRadius.circular(
|
||||
// AppElementSizes.borderRadiusRegular * earlyPercentage,
|
||||
// ),
|
||||
// child: img,
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// // the chapter title
|
||||
// Expanded(
|
||||
// child: Opacity(
|
||||
// opacity: earlyPercentage,
|
||||
// child: Padding(
|
||||
// padding: EdgeInsets.only(
|
||||
// top: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// // horizontal: 16.0,
|
||||
// ),
|
||||
// // child: SizedBox(
|
||||
// // same as the image width
|
||||
// // width: imageSize,
|
||||
// child: currentChapter == null
|
||||
// ? const SizedBox()
|
||||
// : Text(
|
||||
// currentChapter.title,
|
||||
// style: Theme.of(context).textTheme.titleLarge,
|
||||
// maxLines: 1,
|
||||
// overflow: TextOverflow.ellipsis,
|
||||
// ),
|
||||
// // ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// // the book name and author
|
||||
// Expanded(
|
||||
// child: Opacity(
|
||||
// opacity: earlyPercentage,
|
||||
// child: Padding(
|
||||
// padding: EdgeInsets.only(
|
||||
// bottom: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// // horizontal: 16.0,
|
||||
// ),
|
||||
// // child: SizedBox(
|
||||
// // same as the image width
|
||||
// // width: imageSize,
|
||||
// child: Text(
|
||||
// [
|
||||
// currentBookMetadata?.title ?? '',
|
||||
// currentBookMetadata?.authorName ?? '',
|
||||
// ].join(' - '),
|
||||
// style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
// color: Theme.of(context)
|
||||
// .colorScheme
|
||||
// .onSurface
|
||||
// .withValues(alpha: 0.7),
|
||||
// ),
|
||||
// maxLines: 1,
|
||||
// overflow: TextOverflow.ellipsis,
|
||||
// ),
|
||||
// // ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// // the progress bar
|
||||
// Expanded(
|
||||
// child: Opacity(
|
||||
// opacity: earlyPercentage,
|
||||
// child: SizedBox(
|
||||
// width: imageSize,
|
||||
// child: Padding(
|
||||
// padding: EdgeInsets.only(
|
||||
// // top: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// left: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// right: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// ),
|
||||
// child: const AudiobookChapterProgressBar(),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// Expanded(
|
||||
// child: Opacity(
|
||||
// opacity: earlyPercentage,
|
||||
// child: SizedBox(
|
||||
// width: imageSize,
|
||||
// child: Padding(
|
||||
// padding: EdgeInsets.only(
|
||||
// // top: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// left: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// right: AppElementSizes.paddingRegular * earlyPercentage,
|
||||
// ),
|
||||
// child: const AudiobookProgressBar(),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// // the chapter skip buttons, seek 30 seconds back and forward, and play/pause button
|
||||
// Expanded(
|
||||
// flex: 2,
|
||||
// child: Opacity(
|
||||
// opacity: earlyPercentage,
|
||||
// child: SizedBox(
|
||||
// width: imageSize,
|
||||
// height: AppElementSizes.iconSizeRegular,
|
||||
// child: Row(
|
||||
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
// children: [
|
||||
// // previous chapter
|
||||
// const AudiobookPlayerSeekChapterButton(isForward: false),
|
||||
// // buttonSkipBackwards
|
||||
// const AudiobookPlayerSeekButton(isForward: false),
|
||||
// AudiobookPlayerPlayPauseButton(
|
||||
// playPauseController: playPauseController,
|
||||
// ),
|
||||
// // buttonSkipForwards
|
||||
// const AudiobookPlayerSeekButton(isForward: true),
|
||||
// // next chapter
|
||||
// const AudiobookPlayerSeekChapterButton(isForward: true),
|
||||
// ],
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// // speed control, sleep timer, chapter list, and settings
|
||||
// Expanded(
|
||||
// child: Opacity(
|
||||
// opacity: earlyPercentage,
|
||||
// child: SizedBox(
|
||||
// // padding: EdgeInsets.only(
|
||||
// // bottom: AppElementSizes.paddingRegular * 4 * earlyPercentage,
|
||||
// // ),
|
||||
// width: imageSize,
|
||||
// child: Row(
|
||||
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
// children: [
|
||||
// // speed control
|
||||
// const PlayerSpeedAdjustButton(),
|
||||
// const Spacer(),
|
||||
// // sleep timer
|
||||
// const SleepTimerButton(),
|
||||
// const Spacer(),
|
||||
// // chapter list
|
||||
// const ChapterSelectionButton(),
|
||||
// const Spacer(),
|
||||
// // 跳过片头片尾
|
||||
// SkipChapterStartEndButton(),
|
||||
// // settings
|
||||
// // IconButton(
|
||||
// // icon: const Icon(Icons.more_horiz),
|
||||
// // onPressed: () {
|
||||
// // // show toast
|
||||
// // showNotImplementedToast(context);
|
||||
// // },
|
||||
// // ),
|
||||
// ],
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
|
@ -1,155 +0,0 @@
|
|||
// import 'package:flutter/material.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/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/view/audiobook_player.dart';
|
||||
// import 'package:vaani/router/router.dart';
|
||||
|
||||
// class PlayerWhenMinimized extends HookConsumerWidget {
|
||||
// const PlayerWhenMinimized({
|
||||
// super.key,
|
||||
// required this.availWidth,
|
||||
// required this.maxImgSize,
|
||||
// required this.imgWidget,
|
||||
// required this.playPauseController,
|
||||
// required this.percentageMiniplayer,
|
||||
// });
|
||||
|
||||
// final double availWidth;
|
||||
// final double maxImgSize;
|
||||
// final Widget imgWidget;
|
||||
// final AnimationController playPauseController;
|
||||
|
||||
// /// 0 - 1, from minimized to when switched to expanded player
|
||||
// ///
|
||||
// /// by the time 1 is reached only image should be visible in the center of the widget
|
||||
// final double percentageMiniplayer;
|
||||
|
||||
// @override
|
||||
// Widget build(BuildContext context, WidgetRef ref) {
|
||||
// final player = ref.watch(audiobookPlayerProvider);
|
||||
// final currentChapter = ref.watch(currentPlayingChapterProvider);
|
||||
|
||||
// final vanishingPercentage = 1 - percentageMiniplayer;
|
||||
// // final progress =
|
||||
// // useStream(player.slowPositionStreamInBook, initialData: Duration.zero);
|
||||
// final progress =
|
||||
// useStream(player.positionStream, initialData: Duration.zero);
|
||||
|
||||
// final bookMetaExpanded = ref.watch(currentBookMetadataProvider);
|
||||
|
||||
// var barHeight = vanishingPercentage * 3;
|
||||
|
||||
// return Stack(
|
||||
// alignment: Alignment.topCenter,
|
||||
// children: [
|
||||
// Row(
|
||||
// children: [
|
||||
// // image
|
||||
// Padding(
|
||||
// padding: EdgeInsets.only(
|
||||
// left: ((availWidth - maxImgSize) / 2) * percentageMiniplayer,
|
||||
// ),
|
||||
// child: InkWell(
|
||||
// onTap: () {
|
||||
// // navigate to item page
|
||||
// context.pushNamed(
|
||||
// Routes.libraryItem.name,
|
||||
// pathParameters: {
|
||||
// Routes.libraryItem.pathParamName!:
|
||||
// player.book!.libraryItemId,
|
||||
// },
|
||||
// );
|
||||
// },
|
||||
// child: ConstrainedBox(
|
||||
// constraints: BoxConstraints(
|
||||
// maxWidth: maxImgSize,
|
||||
// ),
|
||||
// child: imgWidget,
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// // author and title of the book
|
||||
// Expanded(
|
||||
// child: Padding(
|
||||
// padding: const EdgeInsets.only(left: 8),
|
||||
// child: Column(
|
||||
// crossAxisAlignment: CrossAxisAlignment.start,
|
||||
// mainAxisAlignment: MainAxisAlignment.center,
|
||||
// mainAxisSize: MainAxisSize.min,
|
||||
// children: [
|
||||
// // AutoScrollText(
|
||||
// Text(
|
||||
// '${bookMetaExpanded?.title ?? ''} - ${currentChapter?.title ?? ''}',
|
||||
// maxLines: 1, overflow: TextOverflow.ellipsis,
|
||||
// // velocity:
|
||||
// // const Velocity(pixelsPerSecond: Offset(16, 0)),
|
||||
// style: Theme.of(context).textTheme.bodyLarge,
|
||||
// ),
|
||||
// Text(
|
||||
// bookMetaExpanded?.authorName ?? '',
|
||||
// maxLines: 1,
|
||||
// overflow: TextOverflow.ellipsis,
|
||||
// style: Theme.of(context).textTheme.bodyMedium!.copyWith(
|
||||
// color: Theme.of(context)
|
||||
// .colorScheme
|
||||
// .onSurface
|
||||
// .withValues(alpha: 0.7),
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// // IconButton(
|
||||
// // icon: const Icon(Icons.fullscreen),
|
||||
// // onPressed: () {
|
||||
// // controller.animateToHeight(state: PanelState.MAX);
|
||||
// // },
|
||||
// // ),
|
||||
|
||||
// // rewind button
|
||||
// Opacity(
|
||||
// opacity: vanishingPercentage,
|
||||
// child: Padding(
|
||||
// padding: const EdgeInsets.only(left: 8),
|
||||
// child: IconButton(
|
||||
// icon: const Icon(
|
||||
// Icons.replay_30,
|
||||
// size: AppElementSizes.iconSizeSmall,
|
||||
// ),
|
||||
// onPressed: () {},
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
|
||||
// // play/pause button
|
||||
// Opacity(
|
||||
// opacity: vanishingPercentage,
|
||||
// child: Padding(
|
||||
// padding: const EdgeInsets.only(right: 8),
|
||||
// child: AudiobookPlayerPlayPauseButton(
|
||||
// playPauseController: playPauseController,
|
||||
// ),
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// SizedBox(
|
||||
// height: barHeight,
|
||||
// child: LinearProgressIndicator(
|
||||
// // value: (progress.data ?? Duration.zero).inSeconds /
|
||||
// // player.book!.duration.inSeconds,
|
||||
// value: (progress.data ?? Duration.zero).inSeconds /
|
||||
// (player.duration?.inSeconds ?? 1),
|
||||
// color: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
// backgroundColor: Theme.of(context).colorScheme.primaryContainer,
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
|
||||
class AudiobookPlayerSeekButton extends HookConsumerWidget {
|
||||
const AudiobookPlayerSeekButton({
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
|
||||
class AudiobookPlayerSeekChapterButton extends HookConsumerWidget {
|
||||
const AudiobookPlayerSeekChapterButton({
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.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/view/player_expanded.dart'
|
||||
show pendingPlayerModals;
|
||||
import 'package:vaani/features/player/view/widgets/playing_indicator_icon.dart';
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
|
|||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/features/player/core/player_status.dart';
|
||||
import 'package:vaani/features/player/providers/player_status_provider.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
|
||||
class AudiobookPlayerPlayPauseButton extends HookConsumerWidget {
|
||||
const AudiobookPlayerPlayPauseButton({
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ import 'package:flutter/material.dart';
|
|||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/constants/sizes.dart';
|
||||
import 'package:vaani/features/player/providers/session_provider.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
import 'package:vaani/features/player/providers/currently_playing_provider.dart';
|
||||
|
||||
class AudiobookChapterProgressBar extends HookConsumerWidget {
|
||||
const AudiobookChapterProgressBar({
|
||||
|
|
|
|||
|
|
@ -1,109 +0,0 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:icons_plus/icons_plus.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/session_provider.dart';
|
||||
import 'package:vaani/features/player/view/player_expanded.dart';
|
||||
import 'package:vaani/generated/l10n.dart';
|
||||
import 'package:vaani/settings/view/notification_settings_page.dart';
|
||||
|
||||
class SkipChapterStartEndButton extends HookConsumerWidget {
|
||||
const SkipChapterStartEndButton({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return Tooltip(
|
||||
message: S.of(context).chapterSkip,
|
||||
child: IconButton(
|
||||
// icon: const Icon(Icons.fast_forward_rounded),
|
||||
icon: const Icon(FontAwesome.arrow_right_to_bracket_solid),
|
||||
onPressed: () async {
|
||||
// show toast
|
||||
pendingPlayerModals++;
|
||||
await showModalBottomSheet<bool>(
|
||||
context: context,
|
||||
barrierLabel: S.of(context).chapterSkip,
|
||||
constraints: BoxConstraints(
|
||||
// 40% of the screen height
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.4,
|
||||
),
|
||||
builder: (context) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(8.0),
|
||||
child: PlayerSkipChapterStartEnd(),
|
||||
);
|
||||
},
|
||||
);
|
||||
pendingPlayerModals--;
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PlayerSkipChapterStartEnd extends HookConsumerWidget {
|
||||
const PlayerSkipChapterStartEnd({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final session = ref.watch(sessionProvider);
|
||||
final bookId = session?.libraryItemId ?? '_';
|
||||
final bookSettings = ref.watch(bookSettingsProvider(bookId));
|
||||
return Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
ListTile(
|
||||
title: Text(
|
||||
'${S.of(context).chapterSkipOpen}${bookSettings.playerSettings.skipChapterStart.inSeconds}s',
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: TimeIntervalSlider(
|
||||
defaultValue: bookSettings.playerSettings.skipChapterStart,
|
||||
// defaultValue: const Duration(seconds: 0),
|
||||
min: const Duration(seconds: 0),
|
||||
max: const Duration(seconds: 60),
|
||||
step: const Duration(seconds: 1),
|
||||
onChangedEnd: (interval) {
|
||||
ref
|
||||
.read(
|
||||
bookSettingsProvider(bookId).notifier,
|
||||
)
|
||||
.update(
|
||||
bookSettings.copyWith
|
||||
.playerSettings(skipChapterStart: interval),
|
||||
);
|
||||
ref.read(audiobookPlayerProvider).setClip(start: interval);
|
||||
},
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
title: Text(
|
||||
'${S.of(context).chapterSkipEnd}${bookSettings.playerSettings.skipChapterEnd.inSeconds}s',
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: TimeIntervalSlider(
|
||||
defaultValue: bookSettings.playerSettings.skipChapterEnd,
|
||||
// defaultValue: const Duration(seconds: 0),
|
||||
min: const Duration(seconds: 0),
|
||||
max: const Duration(seconds: 60),
|
||||
step: const Duration(seconds: 1),
|
||||
onChangedEnd: (interval) {
|
||||
ref
|
||||
.read(
|
||||
bookSettingsProvider(bookId).notifier,
|
||||
)
|
||||
.update(
|
||||
bookSettings.copyWith
|
||||
.playerSettings(skipChapterEnd: interval),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ import 'package:vaani/features/per_book_settings/providers/book_settings_provide
|
|||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
import 'package:vaani/features/player/view/player_expanded.dart';
|
||||
import 'package:vaani/features/player/view/widgets/speed_selector.dart';
|
||||
import 'package:vaani/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/features/settings/app_settings_provider.dart';
|
||||
|
||||
final _logger = Logger('PlayerSpeedAdjustButton');
|
||||
|
||||
|
|
@ -16,13 +16,12 @@ class PlayerSpeedAdjustButton extends HookConsumerWidget {
|
|||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final player = ref.watch(audiobookPlayerProvider);
|
||||
final bookId = player.book?.libraryItemId ?? '_';
|
||||
final player = ref.watch(playerProvider);
|
||||
final bookId = player.session?.libraryItemId ?? '_';
|
||||
final bookSettings = ref.watch(bookSettingsProvider(bookId));
|
||||
final appSettings = ref.watch(appSettingsProvider);
|
||||
final notifier = ref.watch(audiobookPlayerProvider.notifier);
|
||||
return TextButton(
|
||||
child: Text('${player.speed}x'),
|
||||
child: Text('${player.player.speed}x'),
|
||||
onPressed: () async {
|
||||
pendingPlayerModals++;
|
||||
_logger.fine('opening speed selector');
|
||||
|
|
@ -32,7 +31,7 @@ class PlayerSpeedAdjustButton extends HookConsumerWidget {
|
|||
builder: (context) {
|
||||
return SpeedSelector(
|
||||
onSpeedSelected: (speed) {
|
||||
notifier.setSpeed(speed);
|
||||
player.setSpeed(speed);
|
||||
if (appSettings.playerSettings.configurePlayerForEveryBook) {
|
||||
ref
|
||||
.read(
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import 'package:flutter_hooks/flutter_hooks.dart';
|
|||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:list_wheel_scroll_view_nls/list_wheel_scroll_view_nls.dart';
|
||||
import 'package:vaani/features/player/providers/audiobook_player.dart';
|
||||
import 'package:vaani/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/features/settings/app_settings_provider.dart';
|
||||
|
||||
const double itemExtent = 25;
|
||||
|
||||
|
|
@ -22,7 +22,7 @@ class SpeedSelector extends HookConsumerWidget {
|
|||
final appSettings = ref.watch(appSettingsProvider);
|
||||
final playerSettings = appSettings.playerSettings;
|
||||
final speeds = playerSettings.speedOptions;
|
||||
final currentSpeed = ref.watch(audiobookPlayerProvider).speed;
|
||||
final currentSpeed = ref.watch(playerProvider).player.speed;
|
||||
final speedState = useState(currentSpeed);
|
||||
|
||||
// hook the onSpeedSelected function to the state
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue