Flutter新手提问; D:
我想播放音频文件并能够设置其音量或暂停它。
函数“ loop”返回类型为Future的变量,但文档(https://github.com/luanpotter/audioplayers/blob/master/doc/audio_cache.md)表示其返回类型AudioPlayer。
Future<AudioPlayer> audioPlayer = audioCache.loop('background_music.mp3');
应该是
AudioPlayer audioPlayer = audioCache.loop('background_music.mp3');
但是如何使用此变量或将其转换为AudioPlayer?
AudioPlayer.pause();
有效但无效 Future.pause();
我的解决方案:
Future<AudioPlayer> audioPlayer = audioCache.loop('background_music.mp3');
audioPlayer.then((player) {
player.setVolume(0.2);
});
答案 0 :(得分:1)
概念
Dart中的 Future
与JS世界中的Promise
类似。期货表明将来某个时候会发生某些事情。最好的部分是,它允许Dart在完成计算之前不阻止程序执行。它允许Dart继续运行应用程序的其他部分,而这些部分通常不依赖于缓慢的计算。例如开始循环播放音频文件。
要循环播放音频文件,您需要做很多事情:
除此之外,读取文件系统是一个相对较慢的操作,因此包装在Future中。 Read more about futures here
但是如何使用此变量或将其转换为AudioPlayer?
await
的未来:AudioPlayer loopingPlayer = await audioCache.loop('somefile');
then
的未来:audioCache.loop('somefile').then((pl) { /* do work here */ });
有效,但Future.pause()无效;
这是因为Future
(一个类)没有方法pause()
。 AudioPlayer
可以。因此,要调用该方法,您必须等待Future中包装的计算完成(在这种情况下,是我上面提到的事情)。