gaucidaniel / native-audio

MIT License
16 stars 7 forks source link

Add ability to play audio from the assets folder #15

Open Sun3 opened 4 years ago

Sun3 commented 4 years ago

Adding the ability to play audio from the local flutter assets folder would be a great addition.

Thank you.

Sun3 commented 4 years ago

ps: For clarification, is this something that you would add? For my scenarios this is a break issue if not implemented.

Thank you.

Sun3 commented 4 years ago

This is something I am temporarily doing until the plugin can actually load local audio assets. I do believe this feature would make the plugin even better.

Temp Fix: You need to import the path_provider package and the dart:io to use the File(). You also need to mark the _playSampleAudio() method async

import 'package:flutter/services.dart'; // rootBundle
import 'dart:io'; // File()
import 'package:path_provider/path_provider.dart'; // getApplicationDocumentsDirectory()

  Future _playSampleAudio() async {
    // Read the Flutter asset file and save it to the Android or iOS Application Documents Folder
    final fileName = 'local_audio_file.mp3';
    var bytesData = await rootBundle.load("assets/audios/$fileName");
    String addDocDirectoryPath = (await getApplicationDocumentsDirectory()).path;
    String filePathAndName = addDocDirectoryPath + '/$fileName';
    await File(filePathAndName).writeAsBytes(bytesData.buffer.asUint8List());

    _audio.play(filePathAndName,
        title: "How The Fashion Industry Is Responding To Climate Change",
        album: "Science Friday",
        artist: "WNYC Studio",
        imageUrl: "https://www.sciencefriday.com/wp-content/uploads/2019/09/clothes-close-min.jpg");
  }

I hope this temporary workaround helps.

Sun3 commented 4 years ago

For the Android plugin side (kotlin) I have used the following code to load a Flutter Audio Asset and play the audio. For the plugin the local audio asset location and name should be passed from the Flutter call. In my code I hard coded the file name for testing purposes.

val assetManager = registrar.context().assets
val key = registrar.lookupKeyForAsset("assets/audios/local_audio_file.mp3")
val fd = assetManager.openFd(key)
println("AFTER openFd ${fd}")

mediaPlayer.setDataSource(fd.fileDescriptor, fd.startOffset, fd.declaredLength)
mediaPlayer.prepare()
mediaPlayer.start()

Thanks,

YaarPatandarAA commented 4 years ago

It should not be too difficult to play local media assets. Like your code, providing the path and knowing that it is local media will be enough to let the media play.

For local media only two things should be required: path to the local media and a flag indicating that this is local media. There should be code to pull the metadata from the local media file, rather than having to provide it manually.

I can work on this if no one has already started, however I will only be able to do so after all the Holidays.