Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play local mp3 file with audioplayer plugin in Flutter

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?

like image 313
granoeste Avatar asked Sep 29 '17 10:09

granoeste


2 Answers

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);
like image 171
Collin Jackson Avatar answered Nov 13 '22 05:11

Collin Jackson


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

like image 4
Sam Upra Avatar answered Nov 13 '22 04:11

Sam Upra