当我单击该框时,音乐运行良好,但是再次单击时,音乐不会停止。然后,如果我再次单击未选中的框,音乐将再次播放,因此一次播放2次!请帮助我停止音乐!
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
InputStream inputStream = getClass().getResourceAsStream("panda - desiigner (donald trump remix).au");
AudioStream audioStream = null;
try {
audioStream = new AudioStream(inputStream);
} catch (IOException ex) {
Logger.getLogger(kekFrame.class.getName()).log(Level.SEVERE, null, ex);
}
int check;
if(jCheckBox1.isSelected() == true){
check = 1;
} else {
check = 0;
}
switch (check) {
case 1 : AudioPlayer.player.start(audioStream);
System.out.println("Music has started playing");
break;
case 0 : AudioPlayer.player.stop(audioStream);
System.out.println("Music has stopped playing");
break;
}
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JCheckBox jCheckBox1;
最佳答案
假设您已正确创建一个Clip,并且可以访问它和一个反射(reflect)JCheckBox状态的 bool(boolean) 值(例如isSelected),则以下简单代码应该可以工作:
if (isSelected)
{
clip.setFramePosition(0);
clip.start();
}
else
{
clip.stop();
}
可以将其包含在JCheckBox的ActionListener中。
有关使用Clips的更多信息,可以在Java教程的“音频线程”中找到,其中包含有关Clips here的详细信息。如果您搜索如何使用Java Clip,则在其他地方有更清晰的示例。官方的音频Java教程强调背景和高级概念,而牺牲了实际示例imho,这使刚起步的我们这些人难以阅读。
不再支持sun.audio.AudioPlayer!即使它可以在您的PC上运行,也不能保证它可以在其他系统上运行。不幸的是,在这种情况下,过时的代码示例存在于博客和非官方的教程中,随着语言的发展以及编写教程的各方不更新或维护其帖子,这种情况可能经常发生。
响应OP的请求,以下是一个改编自我的JavaFX gui的示例。我不再使用Swing,也不希望回头。
在构建JavFX Button的代码中:
btnPlay = new Button("Play");
btnPlay.setOnAction(e -> handlePlay(e));
这将调用以下方法:
private void handlePlay(ActionEvent e)
{
if (!isPlaying)
{
clip.setFramePosition(0);
clip.start();
((Button)e.getSource()).setText("STOP");
isPlaying = true;
}
else
{
clip.stop();
((Button)e.getSource()).setText("PLAY");
isPlaying = false;
}
}
在此代码中,isPlaying是一个实例变量,在这种情况下,它仅告诉我们按钮是打开还是关闭。当按钮仍处于“播放”状态时,剪辑可能会播放到尽头并自行停止。剪辑播放完后,需要连接LineListener才能使按钮切换回去。
也许您可以将上述内容改编成有用的东西?在我看来,JCheckBox的选择是可疑的,而JToggleButton可能是更好的选择。可以为here找到编写Swing Buttons侦听器的示例。
关于java - CheckBox声音停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165042/