102 lines
3.0 KiB
Dart
102 lines
3.0 KiB
Dart
import 'package:didvan/services/media/media.dart';
|
|
import 'package:didvan/services/network/request.dart';
|
|
import 'package:didvan/services/network/request_helper.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:just_audio/just_audio.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:universal_html/html.dart' as html;
|
|
|
|
class VoiceService {
|
|
static final audioPlayer = AudioPlayer();
|
|
static String? src;
|
|
|
|
static Future<Duration?> getDuration({
|
|
required String src,
|
|
}) async {
|
|
final ap = AudioPlayer();
|
|
Duration? duration;
|
|
try {
|
|
if (src.startsWith('/uploads')) {
|
|
final source =
|
|
'${RequestHelper.baseUrl + src}?accessToken=${RequestService.token}';
|
|
if (kIsWeb) {
|
|
final response =
|
|
await http.get(Uri.parse(source.replaceAll('%3A', ':')));
|
|
final bytes = response.bodyBytes;
|
|
final blob = html.Blob([bytes]);
|
|
final blobUrl = html.Url.createObjectUrlFromBlob(blob);
|
|
duration = await ap.setAudioSource(
|
|
AudioSource.uri(Uri.parse(blobUrl)),
|
|
);
|
|
} else {
|
|
final lockCachingAudioSource =
|
|
LockCachingAudioSource(Uri.parse(source));
|
|
|
|
duration = await ap.setAudioSource(lockCachingAudioSource);
|
|
}
|
|
} else if (src.startsWith('blob:')) {
|
|
duration = await ap.setAudioSource(AudioSource.uri(Uri.parse(src)));
|
|
} else {
|
|
duration = await ap.setFilePath(src);
|
|
}
|
|
} catch (e) {
|
|
if (kDebugMode) {
|
|
print('Error setting audio source: $e');
|
|
}
|
|
} finally {
|
|
await ap.dispose();
|
|
}
|
|
|
|
await ap.load();
|
|
|
|
return duration;
|
|
}
|
|
|
|
static Future<void> voiceHelper({required String src}) async {
|
|
try {
|
|
if (VoiceService.src == src) {
|
|
if (audioPlayer.playing) {
|
|
await audioPlayer.pause();
|
|
} else {
|
|
await audioPlayer.play();
|
|
}
|
|
return;
|
|
}
|
|
audioPlayer.stop();
|
|
VoiceService.src = src;
|
|
if (src.startsWith('/uploads')) {
|
|
final source =
|
|
'${RequestHelper.baseUrl + src}?accessToken=${RequestService.token}';
|
|
if (kIsWeb) {
|
|
final response =
|
|
await http.get(Uri.parse(source.replaceAll('%3A', ':')));
|
|
final bytes = response.bodyBytes;
|
|
final blob = html.Blob([bytes]);
|
|
final blobUrl = html.Url.createObjectUrlFromBlob(blob);
|
|
await audioPlayer.setAudioSource(
|
|
AudioSource.uri(Uri.parse(blobUrl)),
|
|
);
|
|
} else {
|
|
final lockCachingAudioSource =
|
|
LockCachingAudioSource(Uri.parse(source));
|
|
|
|
await audioPlayer.setAudioSource(lockCachingAudioSource);
|
|
}
|
|
} else if (src.startsWith('blob:')) {
|
|
await audioPlayer.setAudioSource(AudioSource.uri(Uri.parse(src)));
|
|
} else {
|
|
await audioPlayer.setFilePath(src);
|
|
}
|
|
await audioPlayer.play();
|
|
} catch (e) {
|
|
resetVoicePlayer();
|
|
}
|
|
}
|
|
|
|
static Future<void> resetVoicePlayer() async {
|
|
src = null;
|
|
|
|
await audioPlayer.stop();
|
|
}
|
|
}
|