我有一个 Android 应用程序可以流式传输 MP3 文件并在播放器中播放此文件,但问题是mediaPlayer.prepare();
需要很长时间缓冲并且应用程序冻结,所以我尝试使用prepareAsync();
,但使用此功能我无法让播放器播放下一个文件。
它只是在线播放一个文件;如果我需要播放另一个文件,我必须在播放结束时关闭并重新启动活动。这是我的代码:
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();
}}