Just Audio Flutter插件-如何将持续时间从流侦听器转换为Integer



我正在使用Flutter的Just-Audio插件播放从应用程序中的streambuilder获取的mp3文件。streambuilder返回setClip函数需要的文件的持续时间;

player.setClip(start: Duration(milliseconds: 0), end: Duration(milliseconds: 10);

代替";10〃;,";结束";点应该是文件的持续时间减去500ms。所以我的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);
}

但我需要将提取的持续时间转换为一个整数,以便减去500毫秒。不幸的是,int newevent = event.inMilliseconds;抛出以下错误;

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?'.

我试过这个;

int? newevent = event?.inMilliseconds;

然后;

await player.setClip(start: Duration(milliseconds: 0), end: Duration(milliseconds: newevent));

但我在milliseconds: newevent下得到了这个红线错误;

The argument type 'Duration?' can't be assigned to the parameter type 'int'.

那么,如何将streamlistener中的持续时间作为整数,以便将其用作player.setClip中的终点呢?

出现问题的原因是durationStream返回了一个可为null的持续时间,并且它必须是不可为null才能将其转换为整数。您可以通过null检查将持续时间提升为不可为null的类型。

此外,要只在第一个事件后运行setClip,请使用first而不是listen,并在函数内部移动setClip

player.durationStream.first.then((event) {
if(event != null){
int newevent = event.inMilliseconds - 500;
await player.setClip(start: Duration(milliseconds: 0), end: Duration(milliseconds: newevent);
}
});

最新更新