didvan-app/lib/services/media/voice.dart

66 lines
1.9 KiB
Dart

import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:just_audio/just_audio.dart';
class VoiceService {
static final audioPlayer = AudioPlayer();
static int? index;
static ConcatenatingAudioSource? _playlist;
VoiceService({required final List<AudioSource> audios}) {
_playlist = ConcatenatingAudioSource(
// Start loading next item just before reaching it
useLazyPreparation: true,
// Customise the shuffle algorithm
shuffleOrder: DefaultShuffleOrder(),
// Specify the playlist items
children: audios,
);
}
static Future<Duration?> getDuration({
required String src,
}) async {
if (src.startsWith('/uploads')) {
return await audioPlayer.setUrl(
'${RequestHelper.baseUrl + src}?accessToken=${RequestService.token}');
} else if (src.startsWith('blob:')) {
return await audioPlayer.setAudioSource(AudioSource.uri(Uri.parse(src)));
} else {
return await audioPlayer.setFilePath(src);
}
}
static Future<bool> voiceHelper({required int index}) async {
try {
if (VoiceService.index == index) {
if (audioPlayer.playerState ==
PlayerState(true, ProcessingState.ready)) {
await audioPlayer.pause();
} else {
await audioPlayer.play();
}
return true;
}
VoiceService.index = index;
await audioPlayer.setAudioSource(_playlist!,
initialIndex: index, initialPosition: Duration.zero);
await audioPlayer
.setLoopMode(LoopMode.off); // Set playlist to loop (off|all|one)
await audioPlayer.play();
return true;
} catch (e) {
resetVoicePlayer();
// rethrow;
return false;
}
}
static Future<void> resetVoicePlayer() async {
index = null;
await audioPlayer.stop();
}
}