简体   繁体   中英

Why does the clip doesn't stop?

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++;
    }
}
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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