所以我已经接近终点了,但我不明白为什么会这样。也许是因为编码一段时间后我现在很愚蠢。然而。所以我的程序应该允许两个文件。第一个是 MP3,另一个是 Wav。我让他们去工作。我的意思是,如果我选择 Wav 文件,就会发出声音,如果我选择 mp3,它就会工作,所以没有问题,但现在的问题是,当按“打开”(-> 浏览文件)然后按“播放”时,声音应该会出现,是的,确实如此。所以当我打开另一个文件(例如一首新歌)时。然后按播放。这首歌正在与第一首歌曲一起播放,这使它同时成为两首轨道,我希望它在播放一首歌曲时播放 -> 然后播放。如果我选择新歌曲并按播放,那么第一首歌曲就会消失。我想我很接近但是是的。不过我已经这样做了
static boolean status = true;
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnPlay) {
if(!status) {
clip.start();
lblPlaying.setText("Enjoy the music!");
} else if(status == true) {
mp3_player.play();
lblPlaying.setText("Enjoy the music!");
}
}
}
});
public void Choose() throws IOException {
String userDir = System.getProperty("user.home");
JFileChooser fileChooser = new JFileChooser(userDir +"/Desktop");
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
String ext = selectedFile.getPath();
if(ext.endsWith(".mp3")) { // For mp3
status = true;
mp3_player = new MP3Player(selectedFile);
lblPlayURL.setText(selectedFile.getName());
}
else if(ext.endsWith(".wav")) {
status = false; //For .Wav
try {
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
clip = clip;
stream = AudioSystem.getAudioInputStream(selectedFile);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
lblPlayURL.setText(selectedFile.getName());
}
catch(Exception e) {
//whatevers
}
}
}
}
}
为了让故事更短,我所做的是将 boolean 值设置为 false 的变量。因此,每当 False 运行时,它都会获取 Wav。当 True 时,它的 mp3。但正如我所说。问题在于什么时候坐着。
- 选择歌曲
- 按播放键播放歌曲
- 选择新歌
- 按播放新歌曲(这是我不想播放的第一首歌曲)
我对 boolean 值做错了什么吗?
编辑:忘记添加打开按钮:
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnOpen) {
try {
Choose();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
}
编辑:停止方法 ,
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnStop) {
if(!status) {
clip.stop();
lblPlaying.setText("Nothing plays right now!");
} else if(status == true) {
mp3_player.stop();
lblPlaying.setText("Nothing plays right now!");
}
}
}
});
最佳答案
您需要另一个标志来告诉您是否正在播放。然后在开始播放歌曲之前,检查标志,如果是,则停止任何音乐,然后开始新的音乐。
您本质上存在设计缺陷。系统能够同时播放多首歌曲,它不知道您想停止其中一首。
关于JAVA - boolean 修正 - 按“播放”时仍然继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33659820/