编写一个小型音频播放器,我想让用户在按下相应按钮时播放上一首和下一首歌曲,我使用listview列出所有歌曲
private int currentSongIndex = 0;
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
strNURL = videoMovieArrayList.get(position).getUrl().toString();
strNTITLE = videoMovieArrayList.get(position).getTitle().toString();
if(mediaPlayer!=null && mediaPlayer.isPlaying())
try {
mediaPlayer.stop();
} catch (Exception e) {
}
play(arg1);
textTrack.setText(strNTITLE);
}
});
}
public void play(View view){
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(strNURL);
} catch (IllegalArgumentException e) {
.......................
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
pauseButton.setEnabled(false);
playButton.setEnabled(true);
}
});
}
public void prev(View view){
Toast.makeText(MusicTrackActivity.this, "Previous song !", Toast.LENGTH_LONG).show();
if(currentSongIndex > 0){
// play(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
}else{
// play last song
// playSong(videoMovieArrayList.size() - 1);
currentSongIndex = videoMovieArrayList.size() - 1;
}
}
public void next(View view){
Toast.makeText(MusicTrackActivity.this, "Next song !", Toast.LENGTH_LONG).show();
if(currentSongIndex < (videoMovieArrayList.size() - 1)){
// play(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
// play(0);
currentSongIndex = 0;
}
}
所以现在我的查询是如何切换到下一首歌,每当用户点击下一个按钮时,如上面的代码所示,我只是显示Toast消息
答案 0 :(得分:1)
btnNext.setOnClickListener(new View.OnClickListener() {
int currentSongIndex= 0;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
plysong(songindex);
}
}
});
答案 1 :(得分:0)
您需要跟踪变量中播放的歌曲的索引,例如current
。
假设适配器的基础数据存储了ArrayList
中歌曲的URI,而用户按下了“下一个”,请检查current + 1
是否超出ArrayList
。如果是,请不要播放歌曲。但是,如果没有,请从ArrayList
获取数据,为您的MediaPlayer
重置setDataSource()
和MediaPlayer
。