How to play local audio with audio_service package in Flutter

553

Quoting the package author here:

This plugin does not play audio.

This plugin only wraps around your existing audio code to allow it to work in the background, but it doesn't care how you actually play the audio. It's up to you to use other plugins to play the audio. ...

If you look at the example, you'll see it uses the just_audio plugin to play audio, so a starting point would be for you to consult the documentation of that plugin rather than this plugin (which doesn't play audio). You will find the answers there.

And here:

The id is just a unique id for your media item. As per the documentation:

/// Metadata about an audio item that can be played, or a folder containing 
/// audio items. 
class MediaItem {
  /// A unique id.   
  final String id; 

It is not required to be a URL.

So you can just pass in a local path as the id and then handle it appropriately by just_audio or whatever audio plugin you are using.

MediaItem(
  id: "assets/audio/my_audio.mp3",
  ...
)

In just_audio you would use this string with setAsset().

Share:
553
Suragch
Author by

Suragch

Read my story here: Programming was my god

Updated on December 23, 2022

Comments

  • Suragch
    Suragch over 1 year

    I recently discovered this question in the closed issues of the audio_service package. I had the same question so I am reposting it here for visibility.

    The audio_service package requires you to pass in a MediaItem like so:

    MediaItem(
      id: "https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3",
      album: "Science Friday",
      title: "A Salute To Head-Scratching Science",
      artist: "Science Friday and WNYC Studios",
      duration: Duration(milliseconds: 5739820),
      artUri: "https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg",
    )
    

    If you want to play a local file, though, there is no clear way to do that. How do you play a local audio file?