14

How to play local mp3 file with audioplayer 0.2.0 in Flutter.

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);
}

Can I get local assets path from rootBundle? Can I pay audio from ByteData on audioPlayer?

granoeste
  • 1,531
  • 3
  • 12
  • 15
  • 1
    The package "audioplayers" instead of "audioplayer" has a nice class AudioCache meant exactly for this purpose. More info here: https://github.com/luanpotter/audioplayers/blob/master/doc/audio_cache.md – oidualc Apr 27 '19 at 11:07
  • You can now read about the AudioCache class here: https://github.com/AgeOfLearning/flutter_audioplayers/blob/master/doc/audio_cache.md – F KIng Feb 27 '22 at 05:52

3 Answers3

11

The audioplayer plugin currently only supports network paths and files. You can move an asset to a temporary folder and play it with this code:

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);
Collin Jackson
  • 110,240
  • 31
  • 221
  • 152
4

I have just created a repo in github that uses audioplayers plugin to stream local mp3 files. This player can seek, pause, stop and play local audio

https://github.com/samupra/local_flutter_audio_player

Sam Upra
  • 737
  • 5
  • 12
3

A way that worked for me was to create the assets file and load the mp3 file in to the directory.

Then load the file using the Future

 AudioPlayer audio = await AudioCache.play("filetobeloaded.mp3");
Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40