mirror of
https://github.com/Dr-Blank/Vaani.git
synced 2026-02-16 14:29:35 +00:00
注释未使用包
This commit is contained in:
parent
50a27fdf67
commit
20a3b95edc
48 changed files with 637 additions and 1472 deletions
|
|
@ -1,6 +1,7 @@
|
|||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:vaani/shared/audio_player.dart';
|
||||
import 'package:vaani/features/player/core/abs_audio_player.dart';
|
||||
|
||||
// 对接audio_service
|
||||
class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
|
||||
final AbsAudioPlayer player;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,33 +1,337 @@
|
|||
// // ignore_for_file: public_member_api_docs, sort_constructors_first
|
||||
// // import 'package:just_audio/just_audio.dart';
|
||||
// import 'package:shelfsdk/audiobookshelf_api.dart' as api;
|
||||
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
||||
import 'dart:async';
|
||||
|
||||
// class AbsPlayerState {
|
||||
// api.BookExpanded? book;
|
||||
// // 当前章节
|
||||
// final api.BookChapter? currentChapter;
|
||||
// // 当前音轨序号
|
||||
// final int currentIndex;
|
||||
// final bool playing;
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
|
||||
// AbsPlayerState({
|
||||
// this.book,
|
||||
// this.currentChapter,
|
||||
// this.currentIndex = 0,
|
||||
// this.playing = false,
|
||||
// });
|
||||
import 'package:vaani/features/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/features/settings/models/app_settings.dart';
|
||||
import 'package:vaani/shared/extensions/chapter.dart';
|
||||
import 'package:vaani/shared/extensions/model_conversions.dart';
|
||||
|
||||
// AbsPlayerState copyWith({
|
||||
// api.BookExpanded? book,
|
||||
// api.BookChapter? currentChapter,
|
||||
// int? currentIndex,
|
||||
// bool? playing,
|
||||
// }) {
|
||||
// return AbsPlayerState(
|
||||
// book: book ?? this.book,
|
||||
// currentChapter: currentChapter ?? this.currentChapter,
|
||||
// currentIndex: currentIndex ?? this.currentIndex,
|
||||
// playing: playing ?? this.playing,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
final offset = Duration(milliseconds: 10);
|
||||
|
||||
final _logger = Logger('AbsAudioPlayer');
|
||||
|
||||
/// 音频播放器抽象类
|
||||
abstract class AbsAudioPlayer {
|
||||
final _mediaItemController = BehaviorSubject<MediaItem?>.seeded(null);
|
||||
final playerStateSubject =
|
||||
BehaviorSubject.seeded(AbsPlayerState(false, AbsProcessingState.idle));
|
||||
final _bookStreamController = BehaviorSubject<BookExpanded?>.seeded(null);
|
||||
final chapterStreamController = BehaviorSubject<BookChapter?>.seeded(null);
|
||||
|
||||
BookExpanded? get book => _bookStreamController.nvalue;
|
||||
BookChapter? get currentChapter => chapterStreamController.nvalue;
|
||||
AbsPlayerState get playerState => playerStateSubject.value;
|
||||
Stream<MediaItem?> get mediaItemStream => _mediaItemController.stream;
|
||||
Stream<AbsPlayerState> get playerStateStream => playerStateSubject.stream;
|
||||
|
||||
Future<void> load(
|
||||
BookExpanded book, {
|
||||
required Uri baseUrl,
|
||||
required String token,
|
||||
Duration? initialPosition,
|
||||
List<Uri>? downloadedUris,
|
||||
}) async {
|
||||
if (_bookStreamController.nvalue == book) {
|
||||
_logger.info('Book is the same, doing nothing');
|
||||
return;
|
||||
}
|
||||
_bookStreamController.add(book);
|
||||
final appSettings = loadOrCreateAppSettings();
|
||||
|
||||
final currentTrack = book.findTrackAtTime(initialPosition ?? Duration.zero);
|
||||
final indexTrack = book.tracks.indexOf(currentTrack);
|
||||
final positionInTrack = initialPosition != null
|
||||
? initialPosition - currentTrack.startOffset
|
||||
: null;
|
||||
final title = appSettings.notificationSettings.primaryTitle
|
||||
.formatNotificationTitle(book);
|
||||
final artist = appSettings.notificationSettings.secondaryTitle
|
||||
.formatNotificationTitle(book);
|
||||
chapterStreamController
|
||||
.add(book.findChapterAtTime(initialPosition ?? Duration.zero));
|
||||
final item = MediaItem(
|
||||
id: book.libraryItemId,
|
||||
title: title,
|
||||
artist: artist,
|
||||
duration: currentChapter?.duration ?? book.duration,
|
||||
artUri: Uri.parse(
|
||||
'$baseUrl/api/items/${book.libraryItemId}/cover?token=$token',
|
||||
),
|
||||
);
|
||||
_mediaItemController.sink.add(item);
|
||||
final playlist = book.tracks
|
||||
.map(
|
||||
(track) => _getUri(currentTrack, downloadedUris,
|
||||
baseUrl: baseUrl, token: token),
|
||||
)
|
||||
.toList();
|
||||
await setPlayList(playlist, index: indexTrack, position: positionInTrack);
|
||||
}
|
||||
|
||||
Future<void> setPlayList(
|
||||
List<Uri> playlist, {
|
||||
int? index,
|
||||
Duration? position,
|
||||
});
|
||||
Future<void> play();
|
||||
Future<void> pause();
|
||||
Future<void> playOrPause();
|
||||
|
||||
// 跳到下一章
|
||||
Future<void> next() async {
|
||||
final chapter = currentChapter;
|
||||
if (book == null || chapter == null) {
|
||||
return;
|
||||
}
|
||||
final chapterIndex = book!.chapters.indexOf(chapter);
|
||||
if (chapterIndex < book!.chapters.length - 1) {
|
||||
final nextChapter = book!.chapters[chapterIndex + 1];
|
||||
await seekInBook(nextChapter.start + offset);
|
||||
}
|
||||
}
|
||||
|
||||
// 跳到上一章
|
||||
Future<void> previous() async {
|
||||
final chapter = currentChapter;
|
||||
if (book == null || chapter == null) {
|
||||
return;
|
||||
}
|
||||
final currentIndex = book!.chapters.indexOf(chapter);
|
||||
if (currentIndex > 0) {
|
||||
final prevChapter = book!.chapters[currentIndex - 1];
|
||||
await seekInBook(prevChapter.start + offset);
|
||||
} else {
|
||||
// 已经是第一章,回到开头
|
||||
await seekInBook(Duration.zero);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> seek(Duration position, {int? index});
|
||||
Future<void> seekInBook(Duration position) async {
|
||||
if (book == null) return;
|
||||
// 找到目标位置所在音轨和音轨内的位置
|
||||
final track = book!.findTrackAtTime(position);
|
||||
final index = book!.tracks.indexOf(track);
|
||||
Duration positionInTrack = position - track.startOffset;
|
||||
if (positionInTrack <= Duration.zero) {
|
||||
positionInTrack = offset;
|
||||
}
|
||||
// 切换到目标音轨具体位置
|
||||
await seek(positionInTrack, index: index);
|
||||
}
|
||||
|
||||
Future<void> setSpeed(double speed);
|
||||
Future<void> setVolume(double volume);
|
||||
Future<void> switchChapter(int chapterId) async {
|
||||
if (book == null) return;
|
||||
|
||||
final chapter = book!.chapters.firstWhere(
|
||||
(ch) => ch.id == chapterId,
|
||||
orElse: () => throw Exception('Chapter not found'),
|
||||
);
|
||||
await seekInBook(chapter.start + offset);
|
||||
}
|
||||
|
||||
bool get playing => playerState.playing;
|
||||
Stream<bool> get playingStream;
|
||||
Stream<BookExpanded?> get bookStream => _bookStreamController.stream;
|
||||
Stream<BookChapter?> get chapterStream => chapterStreamController.stream;
|
||||
|
||||
int get currentIndex;
|
||||
double get speed;
|
||||
|
||||
Duration get position;
|
||||
Stream<Duration> get positionStream;
|
||||
|
||||
Duration get positionInChapter {
|
||||
final globalPosition = positionInBook;
|
||||
return globalPosition -
|
||||
(book?.findChapterAtTime(globalPosition).start ?? Duration.zero);
|
||||
}
|
||||
|
||||
Duration get positionInBook =>
|
||||
position + (book?.tracks[currentIndex].startOffset ?? Duration.zero);
|
||||
|
||||
Stream<Duration> get positionInChapterStream =>
|
||||
positionStream.map((position) {
|
||||
return positionInChapter;
|
||||
});
|
||||
|
||||
Stream<Duration> get positionInBookStream => positionStream.map((position) {
|
||||
return positionInBook;
|
||||
});
|
||||
|
||||
Duration get bufferedPosition;
|
||||
Stream<Duration> get bufferedPositionStream;
|
||||
Duration get bufferedPositionInBook =>
|
||||
bufferedPosition +
|
||||
(book?.tracks[currentIndex].startOffset ?? Duration.zero);
|
||||
Stream<Duration> get bufferedPositionInBookStream =>
|
||||
bufferedPositionStream.map((position) {
|
||||
return bufferedPositionInBook;
|
||||
});
|
||||
|
||||
dispose() {
|
||||
_mediaItemController.close();
|
||||
playerStateSubject.close();
|
||||
_bookStreamController.close();
|
||||
chapterStreamController.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Enumerates the different processing states of a player.
|
||||
enum AbsProcessingState {
|
||||
/// The player has not loaded an [AudioSource].
|
||||
idle,
|
||||
|
||||
/// The player is loading an [AudioSource].
|
||||
loading,
|
||||
|
||||
/// The player is buffering audio and unable to play.
|
||||
buffering,
|
||||
|
||||
/// The player is has enough audio buffered and is able to play.
|
||||
ready,
|
||||
|
||||
/// The player has reached the end of the audio.
|
||||
completed,
|
||||
}
|
||||
|
||||
/// Encapsulates the playing and processing states. These two states vary
|
||||
/// orthogonally, and so if [processingState] is [ProcessingState.buffering],
|
||||
/// you can check [playing] to determine whether the buffering occurred while
|
||||
/// the player was playing or while the player was paused.
|
||||
class AbsPlayerState {
|
||||
/// Whether the player will play when [processingState] is
|
||||
/// [ProcessingState.ready].
|
||||
final bool playing;
|
||||
|
||||
/// The current processing state of the player.
|
||||
final AbsProcessingState processingState;
|
||||
|
||||
AbsPlayerState(this.playing, this.processingState);
|
||||
|
||||
@override
|
||||
String toString() => 'playing=$playing,processingState=$processingState';
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(playing, processingState);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other.runtimeType == runtimeType &&
|
||||
other is PlayerState &&
|
||||
other.playing == playing &&
|
||||
other.processingState == processingState;
|
||||
|
||||
AbsPlayerState copyWith({
|
||||
bool? playing,
|
||||
AbsProcessingState? processingState,
|
||||
}) {
|
||||
return AbsPlayerState(
|
||||
playing ?? this.playing,
|
||||
processingState ?? this.processingState,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
/// Backwards compatible extensions on rxdart's ValueStream
|
||||
extension _ValueStreamExtension<T> on ValueStream<T> {
|
||||
/// Backwards compatible version of valueOrNull.
|
||||
T? get nvalue => hasValue ? value : null;
|
||||
}
|
||||
|
||||
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 {
|
||||
BookChapter findChapterAtTime(Duration position) {
|
||||
return chapters.firstWhere(
|
||||
(element) {
|
||||
return element.start <= position && element.end >= position + offset;
|
||||
},
|
||||
orElse: () => chapters.first,
|
||||
);
|
||||
}
|
||||
|
||||
AudioTrack findTrackAtTime(Duration position) {
|
||||
return tracks.firstWhere(
|
||||
(element) {
|
||||
return element.startOffset <= position &&
|
||||
element.startOffset + element.duration >= position + offset;
|
||||
},
|
||||
orElse: () => tracks.first,
|
||||
);
|
||||
}
|
||||
|
||||
int findTrackIndexAtTime(Duration position) {
|
||||
return tracks.indexWhere((element) {
|
||||
return element.startOffset <= position &&
|
||||
element.startOffset + element.duration >= position + offset;
|
||||
});
|
||||
}
|
||||
|
||||
Duration getTrackStartOffset(int index) {
|
||||
return tracks[index].startOffset;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
106
lib/features/player/core/abs_audio_player_mpv.dart
Normal file
106
lib/features/player/core/abs_audio_player_mpv.dart
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import 'dart:async';
|
||||
|
||||
import 'package:media_kit/media_kit.dart' hide PlayerState;
|
||||
import 'package:vaani/features/player/core/abs_audio_player.dart';
|
||||
|
||||
/// 音频播放器 mpv全平台 (media_kit)
|
||||
class AbsMpvAudioPlayer extends AbsAudioPlayer {
|
||||
late Player player;
|
||||
AbsMpvAudioPlayer() {
|
||||
MediaKit.ensureInitialized();
|
||||
player = Player();
|
||||
player.stream.playing.listen((playing) {
|
||||
final state = playerState;
|
||||
playerStateSubject.add(
|
||||
state.copyWith(
|
||||
playing: playing,
|
||||
processingState: playing
|
||||
? state.processingState == AbsProcessingState.idle
|
||||
? AbsProcessingState.ready
|
||||
: state.processingState
|
||||
: player.state.buffering
|
||||
? AbsProcessingState.buffering
|
||||
: player.state.completed
|
||||
? AbsProcessingState.completed
|
||||
: AbsProcessingState.ready,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
@override
|
||||
Duration get bufferedPosition => player.state.buffer;
|
||||
|
||||
@override
|
||||
Stream<Duration> get bufferedPositionStream => player.stream.buffer;
|
||||
|
||||
@override
|
||||
int get currentIndex => player.state.playlist.index;
|
||||
|
||||
@override
|
||||
Future<void> pause() async {
|
||||
await player.pause();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> play() async {
|
||||
await player.play();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> playOrPause() async {
|
||||
await player.playOrPause();
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<bool> get playingStream => player.stream.playing;
|
||||
|
||||
@override
|
||||
Duration get position => player.state.position;
|
||||
|
||||
@override
|
||||
Stream<Duration> get positionStream => player.stream.position;
|
||||
|
||||
@override
|
||||
Future<void> seek(Duration position, {int? index}) async {
|
||||
if (index != null) {
|
||||
final playing = this.playing;
|
||||
await player.jump(index);
|
||||
if (!playing) await player.pause();
|
||||
}
|
||||
await player.seek(position);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setPlayList(
|
||||
List<Uri> playlist, {
|
||||
int? index,
|
||||
Duration? position,
|
||||
}) async {
|
||||
await player.open(
|
||||
Playlist(
|
||||
playlist.map((uri) => Media(uri.toString())).toList(),
|
||||
index: index ?? 0,
|
||||
),
|
||||
play: false,
|
||||
);
|
||||
// 等待open方法加载完成
|
||||
// ignore: unnecessary_null_comparison
|
||||
await player.stream.duration.firstWhere((d) => d != null);
|
||||
if (position != null) {
|
||||
await player.seek(position);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await player.setRate(speed);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setVolume(double volume) async {
|
||||
await player.setVolume(volume * 100);
|
||||
}
|
||||
|
||||
@override
|
||||
double get speed => player.state.rate;
|
||||
}
|
||||
106
lib/features/player/core/abs_audio_player_platform.dart
Normal file
106
lib/features/player/core/abs_audio_player_platform.dart
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:just_audio_media_kit/just_audio_media_kit.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:vaani/features/player/core/abs_audio_player.dart';
|
||||
|
||||
final _logger = Logger('AbsPlatformAudioPlayer');
|
||||
|
||||
/// 音频播放器 平台ios,macos,android (just_audio)
|
||||
class AbsPlatformAudioPlayer extends AbsAudioPlayer {
|
||||
late final AudioPlayer player;
|
||||
AbsPlatformAudioPlayer() {
|
||||
JustAudioMediaKit.ensureInitialized();
|
||||
player = AudioPlayer();
|
||||
player.playerStateStream.listen((state) {
|
||||
playerStateSubject.add(
|
||||
playerState.copyWith(
|
||||
playing: state.playing,
|
||||
processingState: {
|
||||
ProcessingState.idle: AbsProcessingState.idle,
|
||||
ProcessingState.buffering: AbsProcessingState.buffering,
|
||||
ProcessingState.completed: AbsProcessingState.completed,
|
||||
ProcessingState.loading: AbsProcessingState.loading,
|
||||
ProcessingState.ready: AbsProcessingState.ready,
|
||||
}[state.processingState],
|
||||
),
|
||||
);
|
||||
});
|
||||
player.positionStream.distinct().listen((position) {
|
||||
final chapter = book?.findChapterAtTime(positionInBook);
|
||||
if (chapter != currentChapter) {
|
||||
chapterStreamController.add(chapter);
|
||||
}
|
||||
});
|
||||
}
|
||||
@override
|
||||
Duration get bufferedPosition => player.bufferedPosition;
|
||||
|
||||
@override
|
||||
Stream<Duration> get bufferedPositionStream => player.bufferedPositionStream;
|
||||
|
||||
@override
|
||||
int get currentIndex => player.currentIndex ?? 0;
|
||||
|
||||
@override
|
||||
Future<void> pause() async {
|
||||
await player.pause();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> play() async {
|
||||
await player.play();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> playOrPause() async {
|
||||
player.playing ? await player.pause() : await player.play();
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<bool> get playingStream => player.playingStream;
|
||||
|
||||
@override
|
||||
Duration get position => player.position;
|
||||
|
||||
@override
|
||||
Stream<Duration> get positionStream => player.positionStream;
|
||||
|
||||
@override
|
||||
Future<void> seek(Duration position, {int? index}) async {
|
||||
await player.seek(position, index: index);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setPlayList(
|
||||
List<Uri> playlist, {
|
||||
int? index,
|
||||
Duration? position,
|
||||
}) async {
|
||||
List<AudioSource> audioSources =
|
||||
playlist.map((uri) => AudioSource.uri(uri)).toList();
|
||||
await player
|
||||
.setAudioSources(
|
||||
audioSources,
|
||||
preload: true,
|
||||
initialIndex: index,
|
||||
initialPosition: position,
|
||||
)
|
||||
.catchError((error) {
|
||||
_logger.shout('Error in setting audio source: $error');
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await player.setSpeed(speed);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setVolume(double volume) async {
|
||||
await player.setVolume(volume);
|
||||
}
|
||||
|
||||
@override
|
||||
double get speed => player.speed;
|
||||
}
|
||||
|
|
@ -1,468 +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:logging/logging.dart';
|
||||
// import 'package:rxdart/rxdart.dart';
|
||||
// import 'package:shelfsdk/audiobookshelf_api.dart' hide NotificationSettings;
|
||||
// import 'package:vaani/features/player/core/player_status.dart' as core;
|
||||
// import 'package:vaani/features/player/providers/player_status_provider.dart';
|
||||
// import 'package:vaani/features/settings/app_settings_provider.dart';
|
||||
// import 'package:vaani/features/settings/models/app_settings.dart';
|
||||
// import 'package:vaani/shared/extensions/chapter.dart';
|
||||
// import 'package:vaani/shared/extensions/model_conversions.dart';
|
||||
|
||||
// // add a small offset so the display does not show the previous chapter for a split second
|
||||
// final offset = Duration(milliseconds: 10);
|
||||
|
||||
// final _logger = Logger('AudiobookPlayer');
|
||||
|
||||
// class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
|
||||
// final AudioPlayer _player = AudioPlayer();
|
||||
// final Ref ref;
|
||||
|
||||
// BookExpanded? _book;
|
||||
// BookExpanded? get book => _book;
|
||||
|
||||
// late NotificationSettings notificationSettings;
|
||||
|
||||
// final _currentChapterObject = BehaviorSubject<BookChapter?>.seeded(null);
|
||||
// AbsAudioHandler(this.ref) {
|
||||
// notificationSettings = ref.read(appSettingsProvider).notificationSettings;
|
||||
// ref.listen(appSettingsProvider, (a, b) {
|
||||
// if (a?.notificationSettings != b.notificationSettings) {
|
||||
// notificationSettings = b.notificationSettings;
|
||||
// }
|
||||
// });
|
||||
// final statusNotifier = ref.read(playerStatusProvider.notifier);
|
||||
|
||||
// // 转发播放状态
|
||||
// _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
|
||||
// _player.playerStateStream.listen((event) {
|
||||
// if (event.playing) {
|
||||
// statusNotifier.setPlayStatusVerify(core.PlayStatus.playing);
|
||||
// } else {
|
||||
// statusNotifier.setPlayStatusVerify(core.PlayStatus.paused);
|
||||
// }
|
||||
// });
|
||||
// _player.positionStream.distinct().listen((position) {
|
||||
// final chapter = _book?.findChapterAtTime(positionInBook);
|
||||
// if (chapter != currentChapter) {
|
||||
// if (mediaItem.hasValue && chapter != null) {
|
||||
// // updateMediaItem(
|
||||
// // mediaItem.value!.copyWith(
|
||||
// // duration: chapter.duration,
|
||||
// // displayTitle: chapter.title,
|
||||
// // ),
|
||||
// // );
|
||||
// }
|
||||
// _currentChapterObject.sink.add(chapter);
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// // 加载有声书
|
||||
// Future<void> setSourceAudiobook(
|
||||
// BookExpanded book, {
|
||||
// bool preload = true,
|
||||
// required Uri baseUrl,
|
||||
// required String token,
|
||||
// Duration? initialPosition,
|
||||
// List<Uri>? downloadedUris,
|
||||
// required double volume,
|
||||
// required double speed,
|
||||
// }) async {
|
||||
// final appSettings = loadOrCreateAppSettings();
|
||||
// // if (book == null) {
|
||||
// // _book = null;
|
||||
// // _logger.info('Book is null, stopping player');
|
||||
// // return stop();
|
||||
// // }
|
||||
// if (_book == book) {
|
||||
// _logger.info('Book is the same, doing nothing');
|
||||
// return;
|
||||
// }
|
||||
// _book = book;
|
||||
|
||||
// final trackToPlay = book.findTrackAtTime(initialPosition ?? Duration.zero);
|
||||
// final trackToChapter =
|
||||
// book.findChapterAtTime(initialPosition ?? Duration.zero);
|
||||
// final initialIndex = book.tracks.indexOf(trackToPlay);
|
||||
// final initialPositionInTrack = initialPosition != null
|
||||
// ? initialPosition - trackToPlay.startOffset
|
||||
// : null;
|
||||
// final title = appSettings.notificationSettings.primaryTitle
|
||||
// .formatNotificationTitle(book);
|
||||
// final album = appSettings.notificationSettings.secondaryTitle
|
||||
// .formatNotificationTitle(book);
|
||||
|
||||
// // 添加所有音轨
|
||||
// List<AudioSource> audioSources = book.tracks
|
||||
// .map(
|
||||
// (track) => AudioSource.uri(
|
||||
// _getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
|
||||
// ),
|
||||
// )
|
||||
// .toList();
|
||||
|
||||
// final item = MediaItem(
|
||||
// id: book.libraryItemId,
|
||||
// title: title,
|
||||
// album: album,
|
||||
// displayTitle: title,
|
||||
// displaySubtitle: album,
|
||||
// duration: trackToChapter.duration,
|
||||
// artUri: Uri.parse(
|
||||
// '$baseUrl/api/items/${book.libraryItemId}/cover?token=$token',
|
||||
// ),
|
||||
// );
|
||||
// mediaItem.add(item);
|
||||
// await _player
|
||||
// .setAudioSources(
|
||||
// audioSources,
|
||||
// preload: preload,
|
||||
// initialIndex: initialIndex,
|
||||
// initialPosition: initialPositionInTrack,
|
||||
// )
|
||||
// .catchError((error) {
|
||||
// _logger.shout('Error in setting audio source: $error');
|
||||
// return null;
|
||||
// });
|
||||
// await player.seek(initialPositionInTrack, index: initialIndex);
|
||||
// // _player.seek(initialPositionInTrack, index: initialIndex);
|
||||
// setVolume(volume);
|
||||
// setSpeed(speed);
|
||||
// await play();
|
||||
|
||||
// // 恢复上次播放位置(如果有)
|
||||
// // if (initialPosition != null) {
|
||||
// // await seekInBook(initialPosition);
|
||||
// // }
|
||||
// }
|
||||
|
||||
// // // 音轨切换处理
|
||||
// // void _onTrackChanged(int trackIndex) {
|
||||
// // if (_book == null) return;
|
||||
|
||||
// // // 可以在这里处理音轨切换逻辑,比如预加载下一音轨
|
||||
// // // print('切换到音轨: ${_book!.tracks[trackIndex].title}');
|
||||
// // }
|
||||
|
||||
// // 核心功能:跳转到指定章节
|
||||
// Future<void> skipToChapter(int chapterId) async {
|
||||
// if (_book == null) return;
|
||||
|
||||
// final chapter = _book!.chapters.firstWhere(
|
||||
// (ch) => ch.id == chapterId,
|
||||
// orElse: () => throw Exception('Chapter not found'),
|
||||
// );
|
||||
// await seekInBook(chapter.start + offset);
|
||||
// }
|
||||
|
||||
// BookExpanded? get Book => _book;
|
||||
|
||||
// // 当前音轨
|
||||
// AudioTrack? get currentTrack {
|
||||
// if (_book == null || _player.currentIndex == null) {
|
||||
// return null;
|
||||
// }
|
||||
// return _book!.tracks[_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 (_book == null) {
|
||||
// _logger.warning('No book is set, not toggling play/pause');
|
||||
// }
|
||||
// return switch (_player.playerState) {
|
||||
// PlayerState(playing: var isPlaying) => isPlaying ? pause() : play(),
|
||||
// };
|
||||
// }
|
||||
|
||||
// // 播放控制方法
|
||||
// @override
|
||||
// Future<void> play() async {
|
||||
// await _player.play();
|
||||
// }
|
||||
|
||||
// @override
|
||||
// Future<void> pause() async {
|
||||
// await _player.pause();
|
||||
// }
|
||||
|
||||
// // 重写上一曲/下一曲为章节导航
|
||||
// @override
|
||||
// Future<void> skipToNext() async {
|
||||
// if (_book == null) {
|
||||
// // 回退到默认行为
|
||||
// return _player.seekToNext();
|
||||
// }
|
||||
// final chapter = currentChapter;
|
||||
// if (chapter == null) {
|
||||
// // 回退到默认行为
|
||||
// return _player.seekToNext();
|
||||
// }
|
||||
// final chapterIndex = _book!.chapters.indexOf(chapter);
|
||||
// if (chapterIndex < _book!.chapters.length - 1) {
|
||||
// // 跳到下一章
|
||||
// final nextChapter = _book!.chapters[chapterIndex + 1];
|
||||
// await skipToChapter(nextChapter.id);
|
||||
// }
|
||||
// }
|
||||
|
||||
// @override
|
||||
// Future<void> skipToPrevious() async {
|
||||
// final chapter = currentChapter;
|
||||
// if (_book == null || chapter == null) {
|
||||
// return _player.seekToPrevious();
|
||||
// }
|
||||
// final currentIndex = _book!.chapters.indexOf(chapter);
|
||||
// if (currentIndex > 0) {
|
||||
// // 跳到上一章
|
||||
// final prevChapter = _book!.chapters[currentIndex - 1];
|
||||
// await skipToChapter(prevChapter.id);
|
||||
// } else {
|
||||
// // 已经是第一章,回到开头
|
||||
// await seekInBook(Duration.zero);
|
||||
// }
|
||||
// }
|
||||
|
||||
// @override
|
||||
// Future<void> seek(Duration position) async {
|
||||
// // 这个 position 是当前音轨内的位置,我们不直接使用
|
||||
// // 而是通过全局位置来控制
|
||||
// final track = currentTrack;
|
||||
// Duration startOffset = Duration.zero;
|
||||
// if (track != null) {
|
||||
// startOffset = track.startOffset;
|
||||
// }
|
||||
// await seekInBook(startOffset + position);
|
||||
// }
|
||||
|
||||
// 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 (_book == null) return;
|
||||
// // 找到目标音轨和在音轨内的位置
|
||||
// final track = _book!.findTrackAtTime(globalPosition);
|
||||
// final index = _book!.tracks.indexOf(track);
|
||||
// Duration positionInTrack = globalPosition - track.startOffset;
|
||||
// if (positionInTrack < Duration.zero) {
|
||||
// positionInTrack = Duration.zero;
|
||||
// }
|
||||
// // 切换到目标音轨具体位置
|
||||
// await _player.seek(positionInTrack, index: index);
|
||||
// }
|
||||
|
||||
// AudioPlayer get player => _player;
|
||||
// PlaybackState _transformEvent(PlaybackEvent event) {
|
||||
// return PlaybackState(
|
||||
// controls: [
|
||||
// if ((kIsWeb || !Platform.isAndroid) &&
|
||||
// notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.skipToPreviousChapter))
|
||||
// MediaControl.skipToPrevious,
|
||||
// if (notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.rewind))
|
||||
// MediaControl.rewind,
|
||||
// if (_player.playing) MediaControl.pause else MediaControl.play,
|
||||
// if (notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.fastForward))
|
||||
// MediaControl.fastForward,
|
||||
// if ((kIsWeb || !Platform.isAndroid) &&
|
||||
// notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.skipToNextChapter))
|
||||
// MediaControl.skipToNext,
|
||||
// if (notificationSettings.mediaControls
|
||||
// .contains(NotificationMediaControl.stop))
|
||||
// MediaControl.stop,
|
||||
// ],
|
||||
// systemActions: {
|
||||
// // if (kIsWeb || !Platform.isAndroid) MediaAction.skipToPrevious,
|
||||
// // MediaAction.rewind,
|
||||
// MediaAction.seek,
|
||||
// MediaAction.seekForward,
|
||||
// MediaAction.seekBackward,
|
||||
// // MediaAction.fastForward,
|
||||
// // MediaAction.stop,
|
||||
// // MediaAction.setSpeed,
|
||||
// // if (kIsWeb || !Platform.isAndroid) MediaAction.skipToNext,
|
||||
// },
|
||||
// androidCompactActionIndices: const [1, 2, 3],
|
||||
// processingState: const {
|
||||
// ProcessingState.idle: AudioProcessingState.idle,
|
||||
// ProcessingState.loading: AudioProcessingState.loading,
|
||||
// ProcessingState.buffering: AudioProcessingState.buffering,
|
||||
// ProcessingState.ready: AudioProcessingState.ready,
|
||||
// ProcessingState.completed: AudioProcessingState.completed,
|
||||
// }[_player.processingState] ??
|
||||
// AudioProcessingState.idle,
|
||||
// playing: _player.playing,
|
||||
// updatePosition: positionInChapter,
|
||||
// bufferedPosition: _player.bufferedPosition,
|
||||
// speed: _player.speed,
|
||||
// queueIndex: event.currentIndex,
|
||||
// captioningEnabled: false,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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 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 {
|
||||
// BookChapter findChapterAtTime(Duration position) {
|
||||
// return chapters.firstWhere(
|
||||
// (element) {
|
||||
// return element.start <= position && element.end >= position + offset;
|
||||
// },
|
||||
// orElse: () => chapters.first,
|
||||
// );
|
||||
// }
|
||||
|
||||
// AudioTrack findTrackAtTime(Duration position) {
|
||||
// return tracks.firstWhere(
|
||||
// (element) {
|
||||
// return element.startOffset <= position &&
|
||||
// element.startOffset + element.duration >= position + offset;
|
||||
// },
|
||||
// orElse: () => tracks.first,
|
||||
// );
|
||||
// }
|
||||
|
||||
// int findTrackIndexAtTime(Duration position) {
|
||||
// return tracks.indexWhere((element) {
|
||||
// return element.startOffset <= position &&
|
||||
// element.startOffset + element.duration >= position + offset;
|
||||
// });
|
||||
// }
|
||||
|
||||
// Duration getTrackStartOffset(int index) {
|
||||
// return tracks[index].startOffset;
|
||||
// }
|
||||
// }
|
||||
|
|
@ -1,20 +1,19 @@
|
|||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:audio_session/audio_session.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:media_kit/media_kit.dart';
|
||||
import 'package:vaani/features/player/core/abs_audio_handler.dart' as core;
|
||||
import 'package:vaani/features/player/providers/abs_provider.dart';
|
||||
import 'package:vaani/features/player/core/abs_audio_player.dart';
|
||||
import 'package:vaani/globals.dart';
|
||||
|
||||
Future<void> configurePlayer(ProviderContainer container) async {
|
||||
/// 音频播放器 配置
|
||||
Future<void> configurePlayer(AbsAudioPlayer player) async {
|
||||
// for playing audio on windows, linux
|
||||
MediaKit.ensureInitialized();
|
||||
|
||||
// for configuring how this app will interact with other audio apps
|
||||
final session = await AudioSession.instance;
|
||||
await session.configure(const AudioSessionConfiguration.speech());
|
||||
|
||||
await AudioService.init(
|
||||
builder: () => core.AbsAudioHandler(container.read(absAudioPlayerProvider)),
|
||||
builder: () => core.AbsAudioHandler(player),
|
||||
config: const AudioServiceConfig(
|
||||
androidNotificationChannelId: 'dr.blank.vaani.channel.audio',
|
||||
androidNotificationChannelName: 'ABSPlayback',
|
||||
|
|
|
|||
|
|
@ -1,58 +0,0 @@
|
|||
enum PlayStatus { stopped, playing, paused, hidden, loading, completed }
|
||||
|
||||
class PlayerStatus {
|
||||
PlayStatus playStatus;
|
||||
String itemId;
|
||||
bool quite;
|
||||
|
||||
PlayerStatus({
|
||||
this.playStatus = PlayStatus.hidden,
|
||||
this.itemId = '',
|
||||
this.quite = false,
|
||||
}) {
|
||||
// addListener(_onStatusChanged);
|
||||
}
|
||||
bool isPlaying({String? itemId}) {
|
||||
if (itemId != null && this.itemId.isNotEmpty) {
|
||||
return playStatus == PlayStatus.playing && this.itemId == itemId;
|
||||
} else {
|
||||
return playStatus == PlayStatus.playing;
|
||||
}
|
||||
}
|
||||
|
||||
bool isPaused({String? itemId}) {
|
||||
if (itemId != null && this.itemId.isNotEmpty) {
|
||||
return playStatus == PlayStatus.paused && this.itemId == itemId;
|
||||
} else {
|
||||
return playStatus == PlayStatus.paused;
|
||||
}
|
||||
}
|
||||
|
||||
bool isStopped({String? itemId}) {
|
||||
if (itemId != null && this.itemId.isNotEmpty) {
|
||||
return playStatus == PlayStatus.stopped && this.itemId == itemId;
|
||||
} else {
|
||||
return playStatus == PlayStatus.stopped;
|
||||
}
|
||||
}
|
||||
|
||||
bool isLoading(String? itemId) {
|
||||
if (itemId != null && this.itemId.isNotEmpty) {
|
||||
return playStatus == PlayStatus.loading && this.itemId == itemId;
|
||||
} else {
|
||||
return playStatus == PlayStatus.loading;
|
||||
}
|
||||
}
|
||||
|
||||
PlayerStatus copyWith({
|
||||
PlayStatus? playStatus,
|
||||
String? itemId,
|
||||
bool? quite,
|
||||
}) {
|
||||
return PlayerStatus(
|
||||
playStatus: playStatus ?? this.playStatus,
|
||||
itemId: itemId ?? this.itemId,
|
||||
quite: quite ?? this.quite,
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue