所以我正在尝试创建一个音乐播放器小部件,但一次只能播放多个选定的歌曲。我希望增强的for循环将遍历所有选定的文件并一次播放一个,但它同时播放所有歌曲。有没有更好的方法来使这项工作?
FileInputStream FIS;
BufferedInputStream BIS;
public Player player;
public long pauseLocation;
public long songTotalLength;
public boolean playState = false;
public String fileLocation;
public boolean playState(){
return playState;
}
public void setPlayState(boolean value){
this.playState = value;
}
public void select() {
FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3 Files", "mp3", "mpeg3");
JFileChooser chooser = new JFileChooser("D:\\MAIN_DIV\\Music");
chooser.addChoosableFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
stop();
if (playState == false) {
File[] selectedFile = chooser.getSelectedFiles();
for (File x : selectedFile) {
String song = x + "";
String name = chooser.getSelectedFile().getName();
display.setText(name);
play(song);
}
}
}
}
public void play(String path){
playState();
try {
FIS = new FileInputStream(path);
BIS = new BufferedInputStream(FIS);
player = new Player(BIS);
songTotalLength = FIS.available();
fileLocation = path + "";
//System.out.println(path);
} catch (FileNotFoundException | JavaLayerException ex) {
} catch (IOException ex) {
}
new Thread (){
@Override
public void run(){
if(playState == false){
try {
player.play(); //play from start or resume
if (player.isComplete() && MusicPlayer.count==1){
play(fileLocation);
}
if (player.isComplete()){
MusicPlayer.display.setText("");
}
} catch (JavaLayerException ex) {
}
}
}
}.start();
setPlayState(false);
}
答案 0 :(得分:0)
这是问题的原因:
new Thread () { ... } .start();
创建一个在后台运行的线程来播放歌曲。歌曲播放时play
方法返回,让for
- 循环继续拾取新歌。
如果您只保留run
- 方法的正文,它应该按预期工作。这样,歌曲播放是顺序的,play
阻止,直到player.play();
完成。