繁体   English   中英

按钮事件停止声音

[英]Stop sound with button event

我有声音代码,可以在主类中包含的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()来管理事件,而不是使用按钮上的适配器。 对我来说没有真正的优势,它只是一个替代方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM