我刚开始使用Android开发和Java,这是我第一个熟悉Android开发的应用程序。我差不多完成了应用程序,唯一剩下的就是洗牌。我尝试了许多步骤来做到正确,我已经在网上搜索了相关的问题,但我仍然无法做到正确。
这段代码在我的服务类中,播放列表从主要活动传递:
public void setPlayList(ArrayList<SongModel> playlist) {
playList = playlist;
//Arraylist of integer to hold the number of indices
list = new ArrayList<Integer>();
for(int i =0; i <= playList.size();i++){
list.add(i);
}
Collections.shuffle(list, new Random(System.nanoTime()));
}
下面的代码是歌曲的播放方式,这段代码在configPlayBack()方法中,播放歌曲ID中的歌曲:
long item = 0;
item = playList.get(MusicPref.isShuffle(this)? list.get(position): position).getSongId();
播放下一首歌的片段是:
public void playNext() {
position++;
if (position >= playList.size()) {
position = 0;
}
configPlayBack();
}
但是这些歌仍在连续播放。
编辑:
public void configPlayBack(){
prepared = true;
player.reset();
if ( playList.size()>0){
long item = 0;
item = playList.get(MusicPref.isShuffle(this)? list.get(position):position).getSongId();
playItem(item);
}
}
public void playItem(long item){
Uri base = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri trackUri = ContentUris.withAppendedId(base, item);
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e(TAG, "Errror setting data source", e);
}
try{
player.prepare();
}
catch(Exception ee)
{
ee.printStackTrace();
Log.e(TAG, "Error setting data source", ee);
Toast.makeText(getApplicationContext(), "Song corrupt or not supported", Toast.LENGTH_SHORT).show();
ee.printStackTrace();
isReady = false;
}
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
isReady = true;
setPlayState();
getAudioFocus();
mp.start();
updateNotificationPlayer();
updatePlayback();
updateSeek();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
isReady = false;
mp.reset();
playNext();
}
});
}
});
}
答案 0 :(得分:0)
好的,你正在使用
改组新创建的列表 Collections.shuffle(list, new Random(System.nanoTime()));
但您仍在使用旧播放列表
item = playList.get(MusicPref.isShuffle(this)? list.get(position): position).getSongId();
而且我不确定你为什么要使用那条线。将其改为
item = list.get(position).getSongId();