我在Android中使用MediaPlayer。我有来自服务器的歌曲名称和URL的所有列表。当我点击任何项目时,在MediaPlayer中播放来自服务器的歌曲。这是我点击" Listview"播放歌曲的代码。项目
txtEndTimingForMediaPlayer.setText("");
txtStarTimingForMediaPlayer.setText("");
seekBarPlayer.setProgress(0);
// this code is for stop current playing song and release media player
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
// start new song for play
mediaPlayer=new MediaPlayer();
Uri myUri1 = Uri.parse(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(getActivity(), myUri1);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer player) {
playPause=true;
player.start();
mediaFileLengthInMilliseconds = player.getDuration();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
playPause=false;
btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
现在这个代码的问题是我连续点击歌曲,然后同一首歌多次播放。如何避免这种多实例问题。
答案 0 :(得分:1)
我认为当您点击太快而无法播放相同的歌曲时,if(mediaPlayer!=null && mediaPlayer.isPlaying())
不是真的,然后mediaPlayer=new MediaPlayer();
正在创建新的实例和播放歌曲,这将导致多次听到同一首歌曲。调试并检查代码是否输入if (condition)