我在为Java中的简单mp3播放器创建播放列表时苦苦挣扎,但代码却无法正常工作。这是播放列表部分:
FileFilter filter = new FileNameExtensionFilter("MP3 Files", "mp3", "mpeg3");
JFileChooser chooser = new JFileChooser("C:\\Users\\Junior\\Music");
chooser.addChoosableFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION){
//File myFile=chooser.getSelectedFile();
File[] files=chooser.getSelectedFiles();
//String song=myFile+"";
for(int i=0; i<files.length;i++){
name=files[i].getName()+"";//getting song name for display purpose
try {
MC.Stop();//stopping if any file is playing
display.setText(name.substring(0,name.length()-4));//setting name songs in display (without .mp3)
MC.Play(files[i]+"");//from main class i'm calling play method
} catch (IOException e) {//i'm not really catching any exceptions so...
}//end of catch
}//end of for-loop
}//end of if
此代码正在播放所选的最后一首歌曲(即使我选择了多个文件 - 所以最后选择的歌曲也是如此),但不会进入下一首歌曲。
答案 0 :(得分:1)
我认为这可能会帮助您阅读评论。这是我创建的播放列表。它是一个抽象类,所以你需要创建自己的类来扩展这个类,并实现loadSongs
方法
public abstract class Playlist {
public static final int LOOP_NONE = 0;
public static final int LOOP_PLAYLIST = 1;
public static final int LOOP_SONG = 2;
private List<File> songs;
private int playlistPos;
private int loopMode;
private boolean isShuffled;
public Playlist() {
isShuffled = false;
loopMode = 0;
}
protected abstract List<File> loadPlaylist();
public void initPlaylist() {
songs = loadPlaylist();
}
public File getCurrentSong() {
return songs.get(playlistPos);
}
public int getPlaylistPosition() {
return playlistPos;
}
public void setPlaylistPosition(int playlistPos) {
this.playlistPos = playlistPos;
}
public int getPlaylistSize() {
return songs.size();
}
public boolean isFinalSong() {
return playlistPos == songs.size() - 1;
}
public boolean isShuffled() {
return isShuffled;
}
public int getLoopMode() {
return loopMode;
}
public void toggleShuffle() {
setShuffle(!isShuffled);
}
public void toggleLoop() {
loopMode = (loopMode + 1) % 3;
}
public void skipForward() {
playlistPos = (playlistPos + 1) % songs.size();
// Re-shuffle songs each time the playlist loops
if (playlistPos == 0 && isShuffled) {
shuffle();
}
}
public void skipBack() {
playlistPos = playlistPos == 0 ? songs.size() - 1 : playlistPos - 1;
}
public void setLoop(int loopMode) {
this.loopMode = loopMode;
}
public void setShuffle(boolean shuffle) {
this.isShuffled = shuffle;
if (isShuffled) {
shuffle();
}
else {
unshuffle();
}
}
protected void shuffle() {
Collections.shuffle(songs.subList(playlistPos + 1, songs.size()));
}
protected void unshuffle() {
initPlaylist();
}
}
所以你要创建一个这样的子类:
public TestPlaylist extends Playlist {
@Override
protected List<File> loadPlaylist() {
// Show your file chooser, and return the selected files
// as a list.
}
}
要使用它,你会写:
Playlist playlist = new TestPlaylist();
playlist.initPlaylist();
// Do what you want with it, for example:
playlist.setShuffle(true);
MC.play(playlist.getCurrentSong().getAbsolutePath());