一尘不染

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

flutter

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

pubspec.yaml

flutter:
    assets:
    - sounds/music.mp3

主镖

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支付音频吗?


阅读 2101

收藏
2020-08-13

共1个答案

一尘不染

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);
2020-08-13