如何使用 Future<AudioCache>?
How to use Future<AudioCache>?
一个 Flutter 菜鸟的提问 ;D :
我想播放音频文件并能够设置其音量或暂停它。
函数 "loop" returns 是 Future 类型的变量,但文档 (https://github.com/luanpotter/audioplayers/blob/master/doc/audio_cache.md) 说它是 returns 类型的 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);
});
概念
Dart 中的 Future
s 类似于 JS 世界中的 Promise
。期货表示未来某个时间点会发生某事。它最好的部分是它允许 Dart 在计算完成之前不阻塞程序执行。它允许 Dart 保留 运行 应用程序的其他部分,这些部分不依赖于通常很慢的计算。比如开始循环一个音频文件。
要循环播放音频文件,您需要做很多事情:
- 从文件系统加载文件到内存
- 实例化 AudioPlayer
- 为其设置一些属性
除此之外,读取 file-system 是一个相对较慢的操作,因此包装在 Future 中。 Read more about futures here
But how can I work with this variable or convert it to AudioPlayer?
await
未来:AudioPlayer loopingPlayer = await audioCache.loop('somefile');
then
未来:audioCache.loop('somefile').then((pl) { /* do work here */ });
works but not Future.pause();
那是因为Future
(一个class),没有方法pause()
。 AudioPlayer
确实如此。所以要调用那个方法,你必须等待包裹在 Future 中的计算完成(在这种情况下,就是我上面提到的事情)。
一个 Flutter 菜鸟的提问 ;D :
我想播放音频文件并能够设置其音量或暂停它。
函数 "loop" returns 是 Future 类型的变量,但文档 (https://github.com/luanpotter/audioplayers/blob/master/doc/audio_cache.md) 说它是 returns 类型的 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);
});
概念
Dart 中的Future
s 类似于 JS 世界中的 Promise
。期货表示未来某个时间点会发生某事。它最好的部分是它允许 Dart 在计算完成之前不阻塞程序执行。它允许 Dart 保留 运行 应用程序的其他部分,这些部分不依赖于通常很慢的计算。比如开始循环一个音频文件。
要循环播放音频文件,您需要做很多事情:
- 从文件系统加载文件到内存
- 实例化 AudioPlayer
- 为其设置一些属性
除此之外,读取 file-system 是一个相对较慢的操作,因此包装在 Future 中。 Read more about futures here
But how can I work with this variable or convert it to AudioPlayer?
await
未来:AudioPlayer loopingPlayer = await audioCache.loop('somefile');
then
未来:audioCache.loop('somefile').then((pl) { /* do work here */ });
works but not Future.pause();
那是因为Future
(一个class),没有方法pause()
。 AudioPlayer
确实如此。所以要调用那个方法,你必须等待包裹在 Future 中的计算完成(在这种情况下,就是我上面提到的事情)。