【问题标题】:How to play local mp3 file with audioplayer plugin in Flutter如何在 Flutter 中使用音频播放器插件播放本地 mp3 文件
【发布时间】:2017-09-29 10:02:48
【问题描述】:

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

【问题讨论】:

标签: flutter audio-player


【解决方案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);

【讨论】:

  • 非常感谢。我可以用这种方式播放 mp3。
  • 如何设置 assets/sounds/1.mp3 播放?
【解决方案2】:

我刚刚在 github 中创建了一个 repo,它使用 audioplayers 插件来流式传输本地 mp3 文件。此播放器可以搜索、暂停、停止和播放本地音频

https://github.com/samupra/local_flutter_audio_player

【讨论】:

  • 感谢样品
【解决方案3】:

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

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

【讨论】:

  • 如何暂停或停止此音频?使用这种方法
猜你喜欢
  • 1970-01-01
  • 2012-03-28
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
相关资源
最近更新 更多