简体   繁体   中英

How to stop running clip

I tried some topics there about it but music won't stop. My code is and looks fine, but probably I missing something?

public void playMusic(String musicLocation) {
        try {
            File musicPath = new File(musicLocation);
            AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
            Clip clip = AudioSystem.getClip();
            clip.open(audioInput);
            if (musicPath.exists()&&inGame == true) {
                clip.start();
                clip.loop(Clip.LOOP_CONTINUOUSLY);
            } 
            if (musicPath.exists()&&inGame == false) {
                clip.stop();
            }
            else {
                System.out.println("Cannot find audio file!");
                
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

When games begin, and I click on start, inGame value is set up to true and music start playing. When round ends, value inGame is set up to false but my code above seems to not work. Code bellow makes clip start "when I press 's' key"

if (key == 's' || key == 'S') {
                
                inGame = true;
                playMusic(filepath);
                initGame();

            }

Thank you for ideas. edited: I forgot this String filepath = "pacmanMusic.wav";

added due to question:

private void death() {
        pacsLeft--;
        
        if(pacsLeft == 0) {
            inGame = false;
            //createFile();
            
        }
        writeScoreToFile();     
        continueLevel();
    }
    
    private void win() {
        N_GHOSTS--;
        if(N_GHOSTS == 0) {
            inGame = false;
            win_intro++;
        }
        
        continueLevelWin();
    }

I think that the problem is that you are assuming that AudioSystem.getClip() will return the current Clip, and that you can therefore call stop() on the Clip that you just got from getClip() to stop currently playing audio,

As far as I know, every time that you call getClip(), you get a new clip.

So, if you want to stop a currently playing clip, you're going to have to keep a reference to the Clip when you start it playing. Then, to stop that Clip, you'll have to call stop() on that same Clip instance, not a fresh one.

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