2

I've been racking my brains trying to get this looping wav to pause upon a second click, where am i going wrong?

private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                               
        JToggleButton btn = (JToggleButton) evt.getSource(); 
            if (btn.isSelected()) { 
            try { 
                String soundName = "yourSound.wav";
                AudioInputStream audioInputStream = null;
                try {
                    audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
                } catch (UnsupportedAudioFileException | IOException ex) {
                    Logger.getLogger(GEN.class.getName()).log(Level.SEVERE, null, ex);
                }
                Clip clip = null;
                try {
                    clip = AudioSystem.getClip();
                } catch (LineUnavailableException ex) {
                    Logger.getLogger(GEN.class.getName()).log(Level.SEVERE, null, ex);
                }
                clip.open(audioInputStream);
                clip.start();
                clip.loop(100);
            } catch (LineUnavailableException | IOException ex) {
                Logger.getLogger(GEN.class.getName()).log(Level.SEVERE, null, ex);
            }
            } else { 
            try {
} 
Hywel Rees
  • 884
  • 1
  • 15
  • 22
Sc001010tt
  • 33
  • 7
  • Toggle buttons are supposed to have only two states. You can check out [this](http://stackoverflow.com/a/7524627/1572356) SO answer to know how to get the button's state. – boxed__l Mar 16 '17 at 20:03
  • registering the two states isn't an issue, i've tested this with a print out function, my issue is getting the looped audio to stop when the second click is registered – Sc001010tt Mar 16 '17 at 20:07
  • There is a `stop` method available on the Clip object. Define the clip outside the method. If button is not toggled, clip is not null & clip `isRunning()` then `stop()`. – boxed__l Mar 16 '17 at 20:18
  • Thank you so much! i really appreciate you taking time out to lend a hand! i tried defining | private Clip clip; but it was conflicting with the Clip clip = null; was conflicting, simply removing it fixed it and it works like a dream! – Sc001010tt Mar 16 '17 at 20:28

1 Answers1

0

Outline of solution which helped OP:

private Clip clip; // declared outside the method

private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    JToggleButton btn = (JToggleButton) evt.getSource();
    if (btn.isSelected()) {
        // initialize `clip` variable, if not done already
        // call start() if not running
    } else {
        if (clip != null && clip.isRunning()) {
            clip.stop();
        }
    }
}
boxed__l
  • 1,334
  • 1
  • 10
  • 24