Can we stream an audio file via async task in android. give me an example if u have done.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With