mirror of
https://github.com/Dr-Blank/Vaani.git
synced 2026-02-16 22:39:34 +00:00
123
This commit is contained in:
parent
178f3fbdb1
commit
634ffaed8c
27 changed files with 648 additions and 1012 deletions
|
|
@ -1,3 +0,0 @@
|
|||
import 'package:just_audio/just_audio.dart';
|
||||
|
||||
class AudiobookPlayer extends AudioPlayer {}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:vaani/features/player/core/abs_audio_player.dart';
|
||||
|
||||
// 对接audio_service
|
||||
class AbsAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
|
||||
final AbsAudioPlayer _player;
|
||||
|
||||
AbsAudioHandler(AbsAudioPlayer player) : _player = player {
|
||||
player.mediaItemStream.listen((item) {
|
||||
mediaItem.add(item);
|
||||
});
|
||||
// _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
|
||||
|
||||
playbackState.add(
|
||||
playbackState.value.copyWith(
|
||||
controls: [
|
||||
MediaControl.skipToPrevious,
|
||||
// if (player.state.playing) MediaControl.pause else MediaControl.play,
|
||||
// MediaControl.rewind,
|
||||
// MediaControl.fastForward,
|
||||
MediaControl.skipToNext,
|
||||
MediaControl.stop,
|
||||
],
|
||||
systemActions: {
|
||||
MediaAction.play,
|
||||
MediaAction.pause,
|
||||
MediaAction.seek,
|
||||
MediaAction.seekForward,
|
||||
MediaAction.seekBackward,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// 1. 转发播放/暂停状态
|
||||
player.playerStateStream.listen((playerState) {
|
||||
playbackState.add(
|
||||
playbackState.value.copyWith(
|
||||
playing: playerState.playing,
|
||||
// 根据 playing 和实际情况更新 processingState
|
||||
processingState: const {
|
||||
AbsProcessingState.idle: AudioProcessingState.idle,
|
||||
AbsProcessingState.loading: AudioProcessingState.loading,
|
||||
AbsProcessingState.buffering: AudioProcessingState.buffering,
|
||||
AbsProcessingState.ready: AudioProcessingState.ready,
|
||||
AbsProcessingState.completed: AudioProcessingState.completed,
|
||||
}[playerState.processingState] ??
|
||||
AudioProcessingState.idle,
|
||||
),
|
||||
);
|
||||
});
|
||||
// 2. 转发播放位置
|
||||
player.positionStream.listen((Duration position) {
|
||||
playbackState.add(
|
||||
playbackState.value.copyWith(
|
||||
updatePosition: position,
|
||||
),
|
||||
);
|
||||
});
|
||||
// 3. 转发媒体总时长
|
||||
// player.stream.duration.listen((Duration? duration) {
|
||||
// // 当有新的媒体加载时,更新 mediaItem 的 duration
|
||||
// final currentItem = mediaItem.value;
|
||||
// if (currentItem != null && duration != null) {
|
||||
// mediaItem.add(currentItem.copyWith(duration: duration));
|
||||
// }
|
||||
// });
|
||||
// player.stream.completed.listen((bool playing) {
|
||||
// print('播放完成');
|
||||
// });
|
||||
}
|
||||
|
||||
// 播放控制方法重写
|
||||
@override
|
||||
Future<void> play() async {
|
||||
await _player.play();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pause() async {
|
||||
await _player.pause();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> skipToNext() async {
|
||||
await _player.next();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> skipToPrevious() async {
|
||||
await _player.previous();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> seek(Duration position) async {
|
||||
await _player.seek(position);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await _player.setSpeed(speed);
|
||||
}
|
||||
|
||||
Future<void> setVolume(double volume) async {
|
||||
await _player.setVolume(volume);
|
||||
}
|
||||
|
||||
// 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,
|
||||
// if (!(_settingsProvider?['lockSeekingNotification'] ?? false))
|
||||
// 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]!,
|
||||
// playing: _player.playing,
|
||||
// updatePosition: position,
|
||||
// bufferedPosition: _player.bufferedPosition,
|
||||
// speed: _player.speed,
|
||||
// queueIndex: event.currentIndex,
|
||||
// captioningEnabled: false,
|
||||
// );
|
||||
// }
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:collection/collection.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';
|
||||
|
|
@ -16,20 +17,32 @@ 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));
|
||||
class AbsAudioPlayer {
|
||||
late final AudioPlayer _player;
|
||||
AbsAudioPlayer(AudioPlayer player) : _player = player {
|
||||
_player.positionStream.listen((position) {
|
||||
final chapter = currentChapter;
|
||||
if (positionInBook <= (chapter?.start ?? Duration.zero) ||
|
||||
positionInBook >= (chapter?.end ?? Duration.zero)) {
|
||||
final chapter = book?.findChapterAtTime(positionInBook);
|
||||
if (chapter != currentChapter) {
|
||||
// print('当前章节时长: ${currentChapter?.duration}');
|
||||
// print('切换章节时长: ${chapter?.duration}');
|
||||
// print('当前播放音轨时长: ${_player.duration}');
|
||||
chapterStreamController.add(chapter);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
final _bookStreamController = BehaviorSubject<BookExpanded?>.seeded(null);
|
||||
final chapterStreamController = BehaviorSubject<BookChapter?>.seeded(null);
|
||||
|
||||
BookExpanded? get book => _bookStreamController.nvalue;
|
||||
AudioTrack? get currentTrack => book?.tracks[currentIndex];
|
||||
BookChapter? get currentChapter => chapterStreamController.nvalue;
|
||||
AbsPlayerState get playerState => playerStateSubject.value;
|
||||
Stream<MediaItem?> get mediaItemStream => _mediaItemController.stream;
|
||||
Stream<AbsPlayerState> get playerStateStream => playerStateSubject.stream;
|
||||
PlayerState get playerState => _player.playerState;
|
||||
Stream<PlayerState> get playerStateStream => _player.playerStateStream;
|
||||
|
||||
// 加载整本书
|
||||
Future<void> load(
|
||||
|
|
@ -59,43 +72,77 @@ abstract class AbsAudioPlayer {
|
|||
.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(track, downloadedUris, baseUrl: baseUrl, token: token),
|
||||
track.duration
|
||||
// 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',
|
||||
// ),
|
||||
// );
|
||||
|
||||
mediaItem(track) => MediaItem(
|
||||
id: book.libraryItemId + track.index.toString(),
|
||||
title: title,
|
||||
artist: artist,
|
||||
duration: currentChapter?.duration ?? book.duration,
|
||||
artUri: Uri.parse(
|
||||
'$baseUrl/api/items/${book.libraryItemId}/cover?token=$token',
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
await setPlayList(
|
||||
playlist,
|
||||
index: indexTrack,
|
||||
position: positionInTrack,
|
||||
start: start,
|
||||
end: end,
|
||||
);
|
||||
);
|
||||
List<AudioSource> audioSources = start != null && start > Duration.zero ||
|
||||
end != null && end > Duration.zero
|
||||
? book.tracks
|
||||
.map(
|
||||
(track) => ClippingAudioSource(
|
||||
child: AudioSource.uri(
|
||||
_getUri(
|
||||
track,
|
||||
downloadedUris,
|
||||
baseUrl: baseUrl,
|
||||
token: token,
|
||||
),
|
||||
),
|
||||
start: start,
|
||||
end: end == null ? null : track.duration - end,
|
||||
tag: mediaItem(track),
|
||||
),
|
||||
)
|
||||
.toList()
|
||||
: book.tracks
|
||||
.map(
|
||||
(track) => AudioSource.uri(
|
||||
_getUri(track, downloadedUris, baseUrl: baseUrl, token: token),
|
||||
tag: mediaItem(track),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
|
||||
await _player
|
||||
.setAudioSources(
|
||||
audioSources,
|
||||
preload: true,
|
||||
initialIndex: indexTrack,
|
||||
initialPosition: positionInTrack,
|
||||
)
|
||||
.catchError((error) {
|
||||
_logger.shout('Error in setting audio source: $error');
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> setPlayList(
|
||||
List<(Uri, Duration)> playlist, {
|
||||
int? index,
|
||||
Duration? position,
|
||||
Duration? start,
|
||||
Duration? end,
|
||||
});
|
||||
Future<void> play();
|
||||
Future<void> pause();
|
||||
Future<void> playOrPause();
|
||||
Future<void> play() async {
|
||||
await _player.play();
|
||||
}
|
||||
|
||||
Future<void> pause() async {
|
||||
await _player.pause();
|
||||
}
|
||||
|
||||
Future<void> playOrPause() async {
|
||||
_player.playing ? await _player.pause() : await _player.play();
|
||||
}
|
||||
|
||||
// 跳到下一章
|
||||
Future<void> next() async {
|
||||
|
|
@ -126,7 +173,19 @@ abstract class AbsAudioPlayer {
|
|||
}
|
||||
}
|
||||
|
||||
Future<void> seek(Duration position, {int? index});
|
||||
Future<void> seek(Duration position, {int? index}) async {
|
||||
await _player.seek(_addClippingStart(_player.position, add: false),
|
||||
index: index);
|
||||
}
|
||||
|
||||
Future<void> setSpeed(double speed) async {
|
||||
await _player.setSpeed(speed);
|
||||
}
|
||||
|
||||
Future<void> setVolume(double volume) async {
|
||||
await _player.setVolume(volume);
|
||||
}
|
||||
|
||||
Future<void> seekInBook(Duration position) async {
|
||||
if (book == null) return;
|
||||
// 找到目标位置所在音轨和音轨内的位置
|
||||
|
|
@ -140,8 +199,6 @@ abstract class AbsAudioPlayer {
|
|||
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;
|
||||
|
||||
|
|
@ -153,15 +210,18 @@ abstract class AbsAudioPlayer {
|
|||
}
|
||||
|
||||
bool get playing => playerState.playing;
|
||||
Stream<bool> get playingStream;
|
||||
Stream<bool> get playingStream => _player.playingStream;
|
||||
Stream<BookExpanded?> get bookStream => _bookStreamController.stream;
|
||||
Stream<BookChapter?> get chapterStream => chapterStreamController.stream;
|
||||
|
||||
int get currentIndex;
|
||||
double get speed;
|
||||
int get currentIndex => _player.currentIndex ?? 0;
|
||||
double get speed => _player.speed;
|
||||
|
||||
Duration get position;
|
||||
Stream<Duration> get positionStream;
|
||||
Duration get position => _addClippingStart(_player.position);
|
||||
Stream<Duration> get positionStream =>
|
||||
_player.positionStream.where((_) => _player.playing).map((position) {
|
||||
return _addClippingStart(position);
|
||||
});
|
||||
|
||||
Duration get positionInChapter => getPositionInChapter(position);
|
||||
Duration getPositionInChapter(position) {
|
||||
|
|
@ -183,8 +243,8 @@ abstract class AbsAudioPlayer {
|
|||
return positionInBook;
|
||||
});
|
||||
|
||||
Duration get bufferedPosition;
|
||||
Stream<Duration> get bufferedPositionStream;
|
||||
Duration get bufferedPosition => _player.bufferedPosition;
|
||||
Stream<Duration> get bufferedPositionStream => _player.bufferedPositionStream;
|
||||
Duration get bufferedPositionInBook =>
|
||||
bufferedPosition +
|
||||
(book?.tracks[currentIndex].startOffset ?? Duration.zero);
|
||||
|
|
@ -193,70 +253,26 @@ abstract class AbsAudioPlayer {
|
|||
return bufferedPositionInBook;
|
||||
});
|
||||
|
||||
Duration _addClippingStart(Duration position, {bool add = true}) {
|
||||
if (_player.sequenceState.currentSource != null &&
|
||||
_player.sequenceState.currentSource is ClippingAudioSource) {
|
||||
final currentSource =
|
||||
_player.sequenceState.currentSource as ClippingAudioSource;
|
||||
if (currentSource.start != null) {
|
||||
return add
|
||||
? position + currentSource.start!
|
||||
: position - currentSource.start!;
|
||||
}
|
||||
}
|
||||
return position;
|
||||
}
|
||||
|
||||
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, {
|
||||
|
|
@ -280,6 +296,38 @@ extension _ValueStreamExtension<T> on ValueStream<T> {
|
|||
T? get nvalue => hasValue ? value : null;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
extension FormatNotificationTitle on String {
|
||||
String formatNotificationTitle(BookExpanded book) {
|
||||
return replaceAllMapped(
|
||||
|
|
@ -318,49 +366,3 @@ extension NotificationTitleUtils on NotificationTitleType {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
class AudioMetadata {
|
||||
final String album;
|
||||
final String title;
|
||||
final String artist;
|
||||
final String artwork;
|
||||
|
||||
AudioMetadata({
|
||||
required this.album,
|
||||
required this.title,
|
||||
required this.artist,
|
||||
required this.artwork,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,108 +0,0 @@
|
|||
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, Duration)> playlist, {
|
||||
int? index,
|
||||
Duration? position,
|
||||
Duration? start,
|
||||
Duration? end,
|
||||
}) async {
|
||||
await player.open(
|
||||
Playlist(
|
||||
playlist.map((uri) => Media(uri.$1.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;
|
||||
}
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
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() {
|
||||
// 跳转到播放列表指定条目指定位置
|
||||
// prefetch-playlist=yes
|
||||
JustAudioMediaKit.prefetchPlaylist = true;
|
||||
// merge-files=yes
|
||||
// cache=yes
|
||||
// cache-pause-wait=60
|
||||
|
||||
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],
|
||||
),
|
||||
);
|
||||
});
|
||||
positionStream.listen((position) {
|
||||
final chapter = currentChapter;
|
||||
if (positionInBook <= (chapter?.start ?? Duration.zero) ||
|
||||
positionInBook >= (chapter?.end ?? Duration.zero)) {
|
||||
final chapter = book?.findChapterAtTime(positionInBook);
|
||||
if (chapter != currentChapter) {
|
||||
// print('当前章节时长: ${currentChapter?.duration}');
|
||||
// print('切换章节时长: ${chapter?.duration}');
|
||||
// print('当前播放音轨时长: ${_player.duration}');
|
||||
chapterStreamController.add(chapter);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@override
|
||||
Duration get bufferedPosition => _player.bufferedPosition;
|
||||
|
||||
@override
|
||||
Stream<Duration> get bufferedPositionStream => _player.bufferedPositionStream
|
||||
.where(
|
||||
(_) => _player.playerState.processingState == ProcessingState.buffering,
|
||||
)
|
||||
.asBroadcastStream();
|
||||
|
||||
@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 => _addClippingStart(_player.position);
|
||||
|
||||
Duration _addClippingStart(Duration position, {bool add = true}) {
|
||||
if (_player.sequenceState.currentSource != null &&
|
||||
_player.sequenceState.currentSource is ClippingAudioSource) {
|
||||
final currentSource =
|
||||
_player.sequenceState.currentSource as ClippingAudioSource;
|
||||
if (currentSource.start != null) {
|
||||
return add
|
||||
? position + currentSource.start!
|
||||
: position - currentSource.start!;
|
||||
}
|
||||
}
|
||||
return position;
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<Duration> get positionStream =>
|
||||
_player.positionStream.where((_) => _player.playing).map((position) {
|
||||
return _addClippingStart(position);
|
||||
});
|
||||
|
||||
@override
|
||||
Future<void> seek(Duration position, {int? index}) async {
|
||||
await _player.seek(_addClippingStart(position, add: false), index: index);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setPlayList(
|
||||
List<(Uri, Duration)> playlist, {
|
||||
int? index,
|
||||
Duration? position,
|
||||
Duration? start,
|
||||
Duration? end,
|
||||
}) async {
|
||||
List<AudioSource> audioSources = start != null && start > Duration.zero ||
|
||||
end != null && end > Duration.zero
|
||||
? playlist
|
||||
.map(
|
||||
(item) => ClippingAudioSource(
|
||||
child: AudioSource.uri(item.$1),
|
||||
start: start,
|
||||
end: end == null ? null : item.$2 - end,
|
||||
),
|
||||
)
|
||||
.toList()
|
||||
: playlist.map((item) => AudioSource.uri(item.$1)).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;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
super.dispose();
|
||||
_player.dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,62 +1,69 @@
|
|||
// 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/features/settings/app_settings_provider.dart';
|
||||
// import 'package:vaani/features/settings/models/app_settings.dart';
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:audio_session/audio_session.dart';
|
||||
import 'package:just_audio_background/just_audio_background.dart'
|
||||
show JustAudioBackground, NotificationConfig;
|
||||
import 'package:just_audio_media_kit/just_audio_media_kit.dart'
|
||||
show JustAudioMediaKit;
|
||||
import 'package:vaani/features/settings/app_settings_provider.dart';
|
||||
import 'package:vaani/features/settings/models/app_settings.dart';
|
||||
|
||||
// Future<void> configurePlayer() async {
|
||||
// // for playing audio on windows, linux
|
||||
// JustAudioMediaKit.ensureInitialized();
|
||||
Future<void> configurePlayer() async {
|
||||
// for playing audio on windows, linux
|
||||
JustAudioMediaKit.ensureInitialized();
|
||||
|
||||
// // for configuring how this app will interact with other audio apps
|
||||
// final session = await AudioSession.instance;
|
||||
// await session.configure(const AudioSessionConfiguration.speech());
|
||||
// 跳转到播放列表指定条目指定位置
|
||||
// prefetch-playlist=yes
|
||||
// JustAudioMediaKit.prefetchPlaylist = true;
|
||||
// merge-files=yes
|
||||
// cache=yes
|
||||
// cache-pause-wait=60
|
||||
|
||||
// final appSettings = loadOrCreateAppSettings();
|
||||
// for configuring how this app will interact with other audio apps
|
||||
final session = await AudioSession.instance;
|
||||
await session.configure(const AudioSessionConfiguration.speech());
|
||||
|
||||
// // for playing audio in the background
|
||||
// await JustAudioBackground.init(
|
||||
// androidNotificationChannelId: 'dr.blank.vaani.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,
|
||||
// },
|
||||
// );
|
||||
// },
|
||||
// );
|
||||
// }
|
||||
final appSettings = loadOrCreateAppSettings();
|
||||
|
||||
// for playing audio in the background
|
||||
await JustAudioBackground.init(
|
||||
androidNotificationChannelId: 'dr.blank.vaani.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,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue