Why does the clip doesn't stop?

Viewed 36

I'm trying to make music play with one button(First click is play, second is stop, third is play again etc etc). The problem is it does not want to stop. Second click is blank and then third music starts to impose itself. Any suggestions?

public void music() {
    File file = new File("music.wav");
    AudioInputStream audioStream = null;
    Clip clip = null;
    try {
        audioStream = AudioSystem.getAudioInputStream(file);
        clip = AudioSystem.getClip();
        clip.open(audioStream);
    } catch (LineUnavailableException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedAudioFileException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    if (m % 2 == 1) {
        clip.start();
        m++;
    } else {
        clip.stop();
        m++;
    }
}
1 Answers
public void playmusic() {
    if(m%2==1) {
        File file = new File("music.wav");
        AudioInputStream audioStream = null;
        try {
            audioStream = AudioSystem.getAudioInputStream(file);
            clip = AudioSystem.getClip();
            clip.open(audioStream);
        } catch (LineUnavailableException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedAudioFileException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        clip.start();
        m++;
    }
    else {
        clip.stop();
        m++;
    }
}

I did it like this, thanks for helping Karl. To be honest it still feels overly complicated. I just don't know the tools to do it better.

Related