天天看點

Flutter中如何播放flutter中assets目錄下的音頻

flutter中播放音頻可以分為播放flutter中的音頻、手機本地檔案的音頻、和網絡連接配接的音頻

先在pubspec.yaml中添加依賴

然後pub get

播放本地檔案和網絡連接配接的音樂

先建立一個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

播放

player.play('explosion.mp3');

//循環播放
 player.loop('music.mp3');
           

audiocache無法直接使用暫停,但audiocache每次都會生成一個audioplayer執行個體,是以如果你想使用暫停你可以給audiocache設定一個audioplayer執行個體

。再調用該audioplayer執行個體來進行暫停

audioCache.fixedPlayer = audioPlayer;
audioPlayer.pause();
           

以下是官網文檔

AudioPlayers

AudioCache