gpt4 book ai didi

java - 通过按钮事件停止声音

转载 作者:行者123 更新时间:2023-12-03 02:04:44 25 4
gpt4 key购买 nike

我有用于循环播放并在主类中包含的GUI上播放的声音的代码。
主类代码:

public class SoundTest {
public static Clip clip;
public static Mixer mixer;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

StartGUI GUI = new StartGUI();
GUI.setVisible(true);

Mixer.Info[] mixInfos = AudioSystem.getMixerInfo();
mixer = AudioSystem.getMixer(mixInfos[0]);

DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
try{
clip = (Clip)mixer.getLine(dataInfo);
}
catch(LineUnavailableException l){
l.printStackTrace();

}

try{
URL soundURL = Main.class.getResource("/soundtest/8-Bit-Noise-1.wav");
AudioInputStream audioStrim = AudioSystem.getAudioInputStream(soundURL);
clip.open(audioStrim);
}
catch(LineUnavailableException l){
l.printStackTrace();
}
catch(UnsupportedAudioFileException e ){
e.printStackTrace();
}
catch (IOException i){
i.printStackTrace();
}
clip.start();
do{
System.out.println(clip.isActive());
try{
clip.loop(Clip.LOOP_CONTINUOUSLY);
Thread.sleep(50);

}
catch(InterruptedException ie){
ie.printStackTrace();
}
}while(clip.isActive());


}

public void stop() {
clip.stop();
}

}

在我的JFrame类中,我想创建一个按钮事件以停止声音,我尝试在主类中创建一个stop()方法以在按钮中使用它,但到目前为止它不起作用。

JFrame代码:
public class StartGUI extends javax.swing.JFrame {

SoundTest q;

/**
* Creates new form SoundTestGUI
*/
public StartGUI() {
initComponents();
}



private void SoundBtnActionPerformed(java.awt.event.ActionEvent evt){
// TODO add your handling code here:
q.stop();
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {


/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StartGUI().setVisible(true);
}
});
}
}

最佳答案

我认为您可能想尝试调用SoundTest在构造函数中播放。将剪辑停在事件按钮中,然后尝试检查是否已正确注册了侦听器以收听事件。您可以使用actionPerformed()来管理事件,而不是使用按钮上的适配器。对我而言,这没有任何真正的优势,这只是另一种选择。

关于java - 通过按钮事件停止声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28543984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com