oboard

oboard

https://oboard.eu.org/
github
email
tg_channel
medium
twitter
bilibili
steam_profiles
follow

Flutter audioplayers 路徑坑 未處理的例外:無法加載資產:

一開始我是這樣寫的

//發出提示音
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');
```dart
發現有個prefix
在往上看
```dart
 /// 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'));
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。