一开始我是这样写的
//发出提示音
var audioPlayer = AudioPlayer();
audioPlayer.setPlayerMode(PlayerMode.lowLatency);
audioPlayer.setReleaseMode(ReleaseMode.loop);
audioPlayer.play(AssetSource('sounds/1.mp3'));
可是它不停的报错:
Unhandled Exception: Unable to load asset:
这是我的目录
后来在源码中仔细研究了一番
// read local asset from rootBundle
final byteData = await rootBundle.load('$prefix$fileName');
发现有个prefix
在往上看
/// This is the path inside your assets folder where your files lie.
///
/// For example, Flame uses the prefix 'assets/audio/'
/// (you must include the final slash!).
/// The default prefix (if not provided) is 'assets/'
/// Your files will be found at <prefix><fileName> (so the trailing slash is
/// crucial).
String prefix;
AudioCache({this.prefix = 'assets/'});
原来如此,它默认的根目录是assets/
可以选择将音频文件移动到assets/中,也可以直接修改这个perfix
audioPlayer.audioCache.prefix = '';
加上⬆️这一行就可以了
最终代码⬇️
//发出提示音
var audioPlayer = AudioPlayer();
audioPlayer.setPlayerMode(PlayerMode.lowLatency);
audioPlayer.setReleaseMode(ReleaseMode.loop);
audioPlayer.audioCache.prefix = '';
audioPlayer.play(AssetSource('sounds/1.mp3'));