I have an Android app that streams an MP3 file and plays this file in player,
but the problem is mediaPlayer.prepare();
takes a long time buffering and the app freezes
so I tried to use prepareAsync();
, but with this function I can't make the player play the next file.
It just plays a single file online; if I need to play another file I have to close and restart the activity when play ends. This is my code:
public void playMp3(String _link)
{
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
Progressbar.setVisibility(View.INVISIBLE);
play.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
}
updateProgressBar();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.reset();
songProgressBar.setProgress(0);
songProgressBar.setSecondaryProgress(0);
play.setVisibility(View.VISIBLE);
stop.setVisibility(View.GONE);
link = "http://server11.mp3quran.net/hawashi/002.mp3";
playMp3(link);
}
});
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// Toast.makeText(getApplicationContext(), "n" + percent, Toast.LENGTH_LONG).show();
songProgressBar.setSecondaryProgress(percent);
if(percent==100)
{
Progressbar.setVisibility(View.INVISIBLE);
}else if(percent > songProgressBar.getProgress())
{
Progressbar.setVisibility(View.INVISIBLE);
}else
{
Progressbar.setVisibility(View.VISIBLE);
}
}
});
mediaPlayer.reset();
Progressbar.setVisibility(View.VISIBLE);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(_link);
//mediaPlayer.prepare(); // might take long! (for buffering, etc) //@@
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block///
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}