flutterflutter-audioplayers

Flutter audiolpayers


I'm pretty new to Flutter and wanna try pogram an app just for fun and personal use. So I wanna play a MP3 and on my research I found the audioplayers package. All tutorials I could found was from really old versions and I could'nt figure out how to play a simple Audiofile from the phone. I startet with a FilePicker and select a file. Next step was to create an AudioPlayer and play the file, but whatever I've tried it won't work.

final AudioPlayer player = AudioPlayer();
File? selectedFile;

...

Future<File?> selectFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.audio,
      allowedExtensions: ['mp3', 'wav'], // Erlaubte Audio-Dateiformate
    );

    if (result != null) {
      setState(() {
        selectedFile = File(result.files.single.path!);
      });
      return selectedFile;
    }
  }

  void playSelectedFile() async {
    if (selectedFile != null) {
      int result = await player.play(DeviceFileSource(selectedFile!));
   
    }
  }

So thats the code. The main problem is that I don't really understand the audioplayers package and the audioPlayer.play(...) function, especially what format the data in the brackets needs and the different types. audioplayers on git: https://github.com/bluefireteam/audioplayers/blob/main/getting_started.md

Maybe someone can help :3

I've tried many variations to play a little Sound or MP3, but nothing was working. The main problem is to understand the package.


Solution

  • According to the Github page of the project you've mentioned, you can either reference the source by URL or its actual path.

    Notice that if you chose to use the path, you have to add the mp3 files as Assets of your project, meaning you cannot access any other files that are not immediately accessible from your app.

    The assets are defined in your pubspeck.yalm file,

    flutter: 
        assets:
          - songs/file_1.mp3
          - songs/file_2.mp3
          - songs/file_3.mp3
    

    Assets can be called like this within Flutter

    static const url = 'asset:///songs/file_1.mp3';
    

    There are workarounds if you want to play music files from the local storage of your phone. For that, you'll need some file management package, to be able to read files from your device and to set the permission READ_EXTERNAL_STORAGE on Android, and the equivalent for iOs.