I am new one in android development. I have a mp3 audio player code which play mp3 from url. I want to show loading dialog box when media player is buffering on prepare
Here is my Code I show a dialog on prepare but it continuous run and cannot play mp3. I have no idea where i define smp.setOnPreparedListener. Please tell me that can i define this in play function or outside play function. Please Help Me here is my code. Thanks in Advance please
//Play MP3 Function
public void playSong(int naatindex){
// Play song
try {
mp.reset();
mp.setDataSource(naatpaths[naatindex]);
tv = (TextView) this.findViewById(R.id.mywidget);
tv.setSelected(true); // Set focus to the textview
tv.setText(naattitles[naatindex]);
mp.prepare();
mp.start();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and here is my mp.setOnPreparedListener code
ProgressDialog progressDialog = ProgressDialog.show(this,
"Loading Title", "Loading Message");
mp.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss();
}
mp.start();
}
});
In playSong(), you call :
mp.prepare();
mp.start();
If you directly start the player it would crash because it may be not ready to play. Try this:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(naatpaths[naatindex]);
mp.setOnPreparedListener(new OnPreparedListener(){
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
});
mp.prepareAsync(); //this will prepare file a.k.a buffering
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
If it still fails to play, check the stream url. It might be dead. Also try logging the state of the player. Check the stacktrace for any exceptions too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.