Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Async task for audio streaming in android

Can we stream an audio file via async task in android. give me an example if u have done.

like image 427
user1051599 Avatar asked Jan 26 '26 01:01

user1051599


1 Answers

Alright I've struggled with this myself for quite a while, since everyone always told me "just use prepareAsync() and it will work.

However, you will still need to wait until enough has been buffered before trying to start() otherwise you'll get errors and nothing will happen.

First of, let your music-streamer class implement OnPreparedListener. This will be used to check if enough has been buffered before starting to play.

Next, use this piece of code to start the buffering and set the listener:

mediaPlayer.setDataSource(URL here);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(this);

You have now set your listener to check whether or not enough has been buffered. Only one more step to go

public void onPrepared(MediaPlayer mediaplayer) {
    // We now have buffered enough to be able to play
    mediaPlayer.start();
}

The song will now be able to start playing without giving errors and all that.

Good luck!


As for the fact you want to play the music and be able to stop it at any time, you will need to use a Service if you plan on being able to stop your music from all activities. There are a few tutorials about that to be found on the internet.

like image 148
Sander van't Veer Avatar answered Jan 28 '26 15:01

Sander van't Veer