如何在Flutter中使用audioplayer插件播放本地mp3文件

How to play local mp3 file with audioplayer plugin in Flutter

如何在Flutter中使用audioplayer 0.2.0播放本地mp3文件

pubspec.yaml

flutter:
    assets:
    - sounds/music.mp3

main.dart

Future<ByteData> loadAsset() async {
    return await rootBundle.load('sounds/music.mp3');
}

// FIXME: This code is not working.
Future playLocal() async {
    final result = await audioPlayer.play(loadAsset());
    if (result == 1) setState(() => playerState = PlayerState.playing);
}

我可以从 rootBundle 获取本地资源路径吗? 我可以在 audioPlayer 上从 ByteData 支付音频吗?

audioplayer插件目前只支持网络路径和文件。您可以将资产移动到临时文件夹并使用此代码播放:

import 'package:path_provider/path_provider.dart';

...

final file = new File('${(await getTemporaryDirectory()).path}/music.mp3');
await file.writeAsBytes((await loadAsset()).buffer.asUint8List());
final result = await audioPlayer.play(file.path, isLocal: true);

我刚刚在 github 中创建了一个使用音频播放器插件流式传输本地 mp3 文件的存储库。本播放器可以搜索、暂停、停止和播放本地音频

https://github.com/samupra/local_flutter_audio_player

一种对我有用的方法是创建资产文件并将 mp3 文件加载到目录中。

然后使用 Future AudioPlayer 加载文件 audio = await AudioCache.play("filetobeloaded.mp3");