美文网首页
Flutter audioplayers路径坑 Unhandle

Flutter audioplayers路径坑 Unhandle

作者: 一块小板子 | 来源:发表于2022-08-17 16:15 被阅读0次

一开始我是这样写的

//发出提示音
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'));

相关文章

网友评论

      本文标题:Flutter audioplayers路径坑 Unhandle

      本文链接:https://www.haomeiwen.com/subject/ctojgrtx.html