Flutter中如何播放flutter中assets目录下的音频
flutter中播放音频可以分为播放flutter中的音频、手机本地文件的音频、和网络连接的音频
先在pubspec.yaml中添加依赖
audioplayers: ^0.16.1
然后pub get
播放本地文件和网络连接的音乐
先创建一个audioplayer实列
AudioPlayer audioPlayer = AudioPlayer();
播放和暂停
//url是你的本地音乐路径或者网络链接
play() async {
int result = await audioPlayer.play(url);
if (result == 1) {
// success
}
}
//如果是本都文件将isLocal设为true
playLocal() async {
int result = await audioPlayer.play(localPath, isLocal: true);
}
//播放Uint8List形式文件
playLocal() async {
Uint8List byteData = .. // Load audio as a byte array here.
int result = await audioPlayer.playBytes(byteData);
}
//暂停
int result = await audioPlayer.pause();
//停止
int result = await audioPlayer.stop();
播放flutter文件中的音乐
先在assets文件下新建一个sounds文件来存放音乐文件,然后在pubspec.yaml中添加
assets:
- assets/sounds/
然后pub get
audioplayer的官方文档说不能直接用audioplayer播放音乐,必须用AudioCache这个类来播放
For Local Assets, you have to use the AudioCache class (see below).
AudioCache
In order to play Local Assets, you must use the AudioCache class. AudioCache is not available for Flutter Web.
Flutter does not provide an easy way to play audio on your assets, but this class helps a lot. It actually copies the asset to a temporary folder in the device, where it is then played as a Local File.
It works as a cache because it keeps track of the copied files so that you can replay them without delay.
You can find the full documentation for this class here.
初始化AudioCache
AudioCache player = AudioCache();
播放
player.play('explosion.mp3');
//循环播放
player.loop('music.mp3');
audiocache无法直接使用暂停,但audiocache每次都会生成一个audioplayer实例,所以如果你想使用暂停你可以给audiocache设置一个audioplayer实例
。再调用该audioplayer实例来进行暂停
audioCache.fixedPlayer = audioPlayer;
audioPlayer.pause();
以下是官网文档
AudioPlayers
AudioCache
本文地址:https://blog.csdn.net/weixin_44934496/article/details/112526027