lundi 16 février 2015

Stop sound with button event

I have code for sound that loops and plays on my GUI contained in the main class. Main class code:



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();
}


}


In my JFrame class I want to make a button event that will stop the sound, I have tried to make a stop() method in the main class to use it in the button but so far it is not working.


JFrame code:


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);
}
});
}

Aucun commentaire:

Enregistrer un commentaire