fluffychat/lib/pages/chat/events/audio_player.dart

250 lines
7.8 KiB
Dart
Raw Normal View History

//@dart=2.12
2020-03-15 11:27:51 +01:00
import 'dart:async';
2021-04-30 17:22:29 +02:00
import 'dart:io';
2020-03-15 11:27:51 +01:00
import 'package:flutter/material.dart';
2021-10-26 18:50:34 +02:00
import 'package:audioplayers/audioplayers.dart';
2021-02-13 13:27:44 +01:00
import 'package:flutter_gen/gen_l10n/l10n.dart';
2021-10-26 18:50:34 +02:00
import 'package:matrix/matrix.dart';
import 'package:path_provider/path_provider.dart';
import 'package:fluffychat/config/app_config.dart';
2021-10-26 18:50:34 +02:00
import 'package:fluffychat/utils/sentry_controller.dart';
2021-11-09 21:32:16 +01:00
import '../../../utils/matrix_sdk_extensions.dart/event_extension.dart';
2020-03-15 11:27:51 +01:00
2021-04-30 17:22:29 +02:00
class AudioPlayerWidget extends StatefulWidget {
2020-03-15 11:27:51 +01:00
final Color color;
2020-03-29 20:13:25 +02:00
final Event event;
2020-03-15 11:27:51 +01:00
static String? currentId;
2020-03-15 14:15:45 +01:00
const AudioPlayerWidget(this.event, {this.color = Colors.black, Key? key})
2020-03-15 11:27:51 +01:00
: super(key: key);
@override
_AudioPlayerState createState() => _AudioPlayerState();
}
2021-04-14 10:37:15 +02:00
enum AudioPlayerStatus { notDownloaded, downloading, downloaded }
2020-03-15 11:27:51 +01:00
2021-04-30 17:22:29 +02:00
class _AudioPlayerState extends State<AudioPlayerWidget> {
2021-04-14 10:37:15 +02:00
AudioPlayerStatus status = AudioPlayerStatus.notDownloaded;
2021-04-30 17:22:29 +02:00
final AudioPlayer audioPlayer = AudioPlayer();
2020-03-15 11:27:51 +01:00
StreamSubscription? onAudioPositionChanged;
StreamSubscription? onDurationChanged;
StreamSubscription? onPlayerStateChanged;
StreamSubscription? onPlayerError;
2020-03-15 11:27:51 +01:00
String? statusText;
int currentPosition = 0;
2020-03-15 11:27:51 +01:00
double maxPosition = 0;
File? audioFile;
2021-04-30 17:22:29 +02:00
2020-03-15 11:27:51 +01:00
@override
void dispose() {
2021-06-06 10:50:26 +02:00
if (audioPlayer.state == PlayerState.PLAYING) {
2021-04-30 17:22:29 +02:00
audioPlayer.stop();
}
2021-04-30 17:22:29 +02:00
onAudioPositionChanged?.cancel();
onDurationChanged?.cancel();
onPlayerStateChanged?.cancel();
onPlayerError?.cancel();
2020-03-15 11:27:51 +01:00
super.dispose();
}
2020-05-13 15:58:59 +02:00
Future<void> _downloadAction() async {
2021-04-14 10:37:15 +02:00
if (status != AudioPlayerStatus.notDownloaded) return;
setState(() => status = AudioPlayerStatus.downloading);
2020-12-25 09:58:34 +01:00
try {
final matrixFile =
await widget.event.downloadAndDecryptAttachmentCached();
if (matrixFile == null) throw ('Download failed');
2021-04-30 17:22:29 +02:00
final tempDir = await getTemporaryDirectory();
2021-10-30 10:50:36 +02:00
final fileName =
widget.event.content.tryGet<String>('filename') ?? matrixFile.name;
2021-04-30 17:22:29 +02:00
final file = File('${tempDir.path}/$fileName');
await file.writeAsBytes(matrixFile.bytes);
2020-12-25 09:58:34 +01:00
setState(() {
2021-04-30 17:22:29 +02:00
audioFile = file;
2021-04-14 10:37:15 +02:00
status = AudioPlayerStatus.downloaded;
2020-12-25 09:58:34 +01:00
});
_playAction();
} catch (e, s) {
Logs().v('Could not download audio file', e, s);
2021-05-23 13:11:55 +02:00
ScaffoldMessenger.of(context).showSnackBar(
2021-04-03 13:09:20 +02:00
SnackBar(
2021-08-29 15:18:02 +02:00
content: Text(e.toString()),
2021-04-03 13:09:20 +02:00
),
);
2020-12-25 09:58:34 +01:00
}
2020-03-15 11:27:51 +01:00
}
2020-05-13 15:58:59 +02:00
void _playAction() async {
2021-04-30 17:22:29 +02:00
if (AudioPlayerWidget.currentId != widget.event.eventId) {
if (AudioPlayerWidget.currentId != null) {
2021-06-06 10:50:26 +02:00
if (audioPlayer.state != PlayerState.STOPPED) {
2021-04-30 17:22:29 +02:00
await audioPlayer.stop();
setState(() {});
2020-03-15 12:00:25 +01:00
}
}
2021-04-30 17:22:29 +02:00
AudioPlayerWidget.currentId = widget.event.eventId;
2020-03-15 12:00:25 +01:00
}
2021-04-30 17:22:29 +02:00
switch (audioPlayer.state) {
2021-06-06 10:50:26 +02:00
case PlayerState.PLAYING:
2021-04-30 17:22:29 +02:00
await audioPlayer.pause();
2020-03-15 11:27:51 +01:00
break;
2021-06-06 10:50:26 +02:00
case PlayerState.PAUSED:
2021-04-30 17:22:29 +02:00
await audioPlayer.resume();
2020-03-15 11:27:51 +01:00
break;
2021-06-06 10:50:26 +02:00
case PlayerState.STOPPED:
default:
2021-04-30 17:22:29 +02:00
onAudioPositionChanged ??=
audioPlayer.onAudioPositionChanged.listen((state) {
2021-05-01 15:45:48 +02:00
setState(() {
statusText =
'${state.inMinutes.toString().padLeft(2, '0')}:${(state.inSeconds % 60).toString().padLeft(2, '0')}';
currentPosition =
((state.inMilliseconds.toDouble() / maxPosition) * 100).round();
2021-05-01 15:45:48 +02:00
});
2020-03-15 11:27:51 +01:00
});
2021-04-30 17:22:29 +02:00
onDurationChanged ??= audioPlayer.onDurationChanged.listen((max) =>
setState(() => maxPosition = max.inMilliseconds.toDouble()));
onPlayerStateChanged ??=
audioPlayer.onPlayerStateChanged.listen((_) => setState(() {}));
2021-04-30 17:22:29 +02:00
onPlayerError ??= audioPlayer.onPlayerError.listen((e) {
2021-05-23 13:11:55 +02:00
ScaffoldMessenger.of(context).showSnackBar(
2021-04-30 17:22:29 +02:00
SnackBar(
content: Text(L10n.of(context)!.oopsSomethingWentWrong),
2021-04-30 17:22:29 +02:00
),
);
SentryController.captureException(e, StackTrace.current);
});
await audioPlayer.play(audioFile!.path);
2020-03-15 11:27:51 +01:00
break;
}
}
static const double buttonSize = 36;
String? get _durationString {
final durationInt = widget.event.content
.tryGetMap<String, dynamic>('info')
?.tryGet<int>('duration');
if (durationInt == null) return null;
final duration = Duration(milliseconds: durationInt);
return '${duration.inMinutes.toString().padLeft(2, '0')}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
2022-01-01 16:23:17 +01:00
List<int> _getWaveform() {
final eventWaveForm = widget.event.content
.tryGetMap<String, dynamic>('org.matrix.msc1767.audio')
?.tryGetList<int>('waveform');
if (eventWaveForm == null) {
return List<int>.filled(100, 500);
}
while (eventWaveForm.length < 100) {
for (var i = 0; i < eventWaveForm.length; i = i + 2) {
eventWaveForm.insert(i, eventWaveForm[i]);
}
}
var i = 0;
final step = (eventWaveForm.length / 100).round();
while (eventWaveForm.length > 100) {
eventWaveForm.removeAt(i);
i = (i + step) % 100;
}
return eventWaveForm;
}
2022-01-01 16:23:17 +01:00
late final List<int> waveform;
@override
void initState() {
super.initState();
waveform = _getWaveform();
}
2020-03-15 11:27:51 +01:00
@override
Widget build(BuildContext context) {
final statusText = this.statusText ??= _durationString ?? '00:00';
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 6.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
width: buttonSize,
height: buttonSize,
child: status == AudioPlayerStatus.downloading
? CircularProgressIndicator(strokeWidth: 2, color: widget.color)
: InkWell(
borderRadius: BorderRadius.circular(64),
child: Material(
color: widget.color.withAlpha(64),
borderRadius: BorderRadius.circular(64),
child: Icon(
audioPlayer.state == PlayerState.PLAYING
? Icons.pause_outlined
: Icons.play_arrow_outlined,
color: widget.color,
),
),
onLongPress: () => widget.event.saveFile(context),
onTap: () {
if (status == AudioPlayerStatus.downloaded) {
_playAction();
} else {
_downloadAction();
}
},
2020-03-15 11:27:51 +01:00
),
2020-03-15 11:47:35 +01:00
),
const SizedBox(width: 8),
Expanded(
child: Row(
children: [
for (var i = 0; i < 100; i++)
Expanded(
child: InkWell(
onTap: () => audioPlayer.seek(Duration(
milliseconds: (maxPosition / 100).round() * i)),
child: Opacity(
opacity: currentPosition > i ? 1 : 0.5,
child: Container(
margin: const EdgeInsets.only(left: 2),
decoration: BoxDecoration(
color: widget.color,
borderRadius:
BorderRadius.circular(AppConfig.borderRadius),
),
height: 64 * (waveform[i] / 1024)),
),
),
)
],
),
2020-03-15 11:27:51 +01:00
),
const SizedBox(width: 8),
Container(
alignment: Alignment.centerRight,
width: 42,
child: Text(
statusText,
style: TextStyle(
color: widget.color,
),
),
),
],
),
2020-03-15 11:27:51 +01:00
);
}
}