我通过网址播放音乐效果很好,但是及时获取getDuration只会返回0.
我的代码:
String AudioURL = link;
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaplayer.setDataSource(AudioURL);
mediaplayer.prepare();
} 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();
}
mediaplayer.start();
mediaplayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Log.e("error", "total duration: " + mp.getDuration());
musica.progre.setProgress(0);
Log.e("MusicPP",""+mp.getDuration());
musica.progre.setMax(mp.getDuration());
Toast toast= Toast.makeText(musica.context,
"duration: "+mp.getDuration(), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
int duration = buscaMusica.mediaplayer.getDuration();
musica.totalTempo.setText(musica.getTimeString(duration));
}
});
mediaplayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
musica.progre.setSecondaryProgress(mediaplayer.getCurrentPosition());
}
});
答案 0 :(得分:0)
使用MediaPlayer
将网址设置为AsyncTask
,如下所示,因此在onPostExecute
中,您将使用getDuration
方法获取持续时间:
private class Load extends AsyncTask<Void , Void , Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
helper.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
mediaPlayer = MediaPlayer.create(getActivity() , uri);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
helper.hide();
seekBar.setProgress(0);
if (mediaPlayer!=null)
{
seekBar.setMax(mediaPlayer.getDuration());
}
else{
getActivity().finish();
Toast.makeText(getActivity(), "Unable to load Announcement, try again later.",Toast.LENGTH_LONG).show();
}
seekBar.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
seekChange(v);
return false;
}
});
}
}