I'm using Flutter's Just-Audio
plugin to play an mp3 file fetched from a streambuilder
in my app. The streambuilder
returns the duration of the file which I need for the setClip
function;
player.setClip(start: Duration(milliseconds: 0), end: Duration(milliseconds: 10);
Instead of "10", the "end" point should be the file's duration minus 500ms. So I've got this stream listener in my initState
;
@override
void initState() {
super.initState();
_init();
}
Future<void> _init() async {
await player.setUrl('https://bucket.s3.amazonaws.com/example.mp3');
player.durationStream.listen((event) {
int newevent = event.inMilliseconds;
});
await player.setClip(start: Duration(milliseconds: 0), end: newevent);
}
But I need to convert the fetched duration to an integer in order to take off 500ms. Unfortunately the int newevent = event.inMilliseconds;
throws the following error;
A value of type 'int' can't be assigned to a variable of type 'Duration?'. Try changing the type of the variable, or casting the right-hand type to 'Duration?'.
I've tried this;
int? newevent = event?.inMilliseconds;
and then;
await player.setClip(start: Duration(milliseconds: 0), end: Duration(milliseconds: newevent));
But then I just get this redline error under milliseconds: newevent
;
The argument type 'Duration?' can't be assigned to the parameter type 'int'.
So how can I get my duration from my streamlistener as an integer so I can use it as the end point in player.setClip
?
The problem appears because durationStream returns a nullable duration, and it has to be non-nullable to be able to convert it to an integer. You can promote the duration to a non-nullable type with a null check.
Furthermore, to only run setClip after the first event, use first
instead of listen
and move setClip
inside the function:
player.durationStream.first.then((event) {
if(event != null){
int newevent = event.inMilliseconds - 500;
await player.setClip(start: Duration(milliseconds: 0), end: Duration(milliseconds: newevent);
}
});