Stopping my playing music in Java

304 views Asked by At

I am writing a programm and I added some background music to it. However I would like to be able to stop the music by the click of a button. I know how to add buttons and stuff however I don't know how to stop the music, I have tried a lot of things but just can't get it to work.

This is my code:

new Thread(new Runnable() {
                    public void run() {
                      try {
                        Clip Music = AudioSystem.getClip();
                        AudioInputStream BMG = AudioSystem.getAudioInputStream(
                          Main.class.getResourceAsStream("/Music/BackgroundMusic.wav"));
                        Music.open(BMG);
                        Music.start(); 
                      } catch (Exception e) {
                        System.err.println(e.getMessage());
                      }
                    }
                  }).start();

If you could help that would be awesome!

Thank you in advance, JS

1

There are 1 answers

0
SteveL On
    Clip Music=null;
    new Thread(new Runnable() {
        public void run() {
          try {
            Clip Music = AudioSystem.getClip();
            AudioInputStream BMG = AudioSystem.getAudioInputStream(
              Main.class.getResourceAsStream("/Music/BackgroundMusic.wav"));
            Music.open(BMG);
            Music.start(); 

          } catch (Exception e) {
            System.err.println(e.getMessage());
          }
        }
      }).start();

    //this goes inside the actionPerformed event of the button
    if(Music!=null)Music.stop();

And as m0skit0 said you better start your variables with a lowercase letter,don't be a c# smug.