'Play Audio in Flutter from URL

I am new to flutter and I want to play audio file from URL path with play, pause and seek button and also show notification in player.



Solution 1:[1]

You can use audioplayers package.

Define AudioPlayer instance like this

AudioPlayer audioPlayer = AudioPlayer();

Play audio as shown below

  play() async {
    int result = await audioPlayer.play(url);
    if (result == 1) {
      // success
    }
  }

You can pause and stop like this

await audioPlayer.pause();
await audioPlayer.stop();

This is how you can play local audio

 playLocal() async {
    int result = await audioPlayer.play(localPath, isLocal: true);
  }

I recommend you to use audio_service package. This is highly customizable with notification and you can also play audio in background or sleep mode.

Solution 2:[2]

You can play a URL in just_audio like this:

final player = AudioPlayer();
await player.setUrl('https://example.com/song.mp3');
player.play();
player.pause();
player.seek(Duration(seconds: 143);

To add notification support, the easiest way is to add just_audio_background. You need to change the above code slightly so that instead of calling setUrl, you now do this:

await player.setAudioSource(AudioSource.uri(
  'https://example.com/song.mp3',
  tag: MediaItem(
    id: 'Some unique ID',
    title: 'Song title',
    album: 'Song album',
    artUri: Uri.parse('https://example.com/art.jpg'),
  ),
));

Now once that song starts playing, the supplied metadata will also be shown in the notification.

just_audio_background must also be initialised in your main:

Future<void> main() async {
  await JustAudioBackground.init(/* See API for options */);
  runApp(MyApp());
}

And don't forget to follow the platform-specific setup instructions for each plugin:

Note that just_audio_background uses the audio_service plugin under the hood, so if your app has more complex requirements, you could use that plugin directly.

If you have questions about how to build the actual UI, you can create a separate question on that, or you can look at the above two links because each plugin includes an example app which demonstrates how to link it all up in a UI.

Solution 3:[3]

Open AndroidManifest.xml file and enable internet permission ,usesCleartextTraffic

android\app\src\main\AndroidManifest.xml

Add following 2 lines for enabling internet permission and usesCleartextTraffic

screenshot of manifest.xml file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hemal Moradiya
Solution 2 Ryan Heise
Solution 3 Rahul Raj