-1

I'm very new and don't know how to stop my Music in another class. My idea was that I push one button and the music should stop.

public class Musik {
    public static synchronized void music(String song) {
        final String songname= song;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try{

                        Clip clip = AudioSystem.getClip();
                        AudioInputStream input=AudioSystem.getAudioInputStream(new File(songname));
                        clip.open(input);
                        clip.loop(clip.LOOP_CONTINUOUSLY);
                        Thread.sleep(clip.getMicrosecondLength()/1000);


                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        
    }
} 

I want in the button that the music stops, but I don't have any clue. stop();, close(); or something like that doesn't function at all.

public void actionPerformed(ActionEvent e){
    if (button==e.getSource()){
       //Musik.close(); doesnt work
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You need to place the definition of the `Clip` outside the `music` method. Or assign the thread to a variable and kill that. – Fullslack Dec 26 '20 at 21:58

1 Answers1

1

You can implement a boolean as a flag. Instead of while(true), create a boolean maybe called isPlaying. And make it while(isPlaying). Create a function close that sets the boolean to false

Alwin Brauns
  • 129
  • 8