简体   繁体   中英

Stop sound from playing in Java

i got a really specific question. Im creating a game right now and want it to play some music. Right now the music starts when i press X.

if (keyCode == KeyEvent.VK_X) {
        PlaySound pl = new PlaySound(//Play testsound
                new File(
                        "C:\\Users\\Desktop\\Projekt MC\\Musik\\WAV\\dungeontest.wav"));
        pl.start();

And i would like the sound to stop playing when i press X again. I already testet to create an boolean who is saying if music is playing. But that also failed.

Would be happy if anyone got an idea how to solve this problem.

Your PlaySound variable, pl, is local to this block of code and thus is invisible to the rest of the program. You want instead to make this field a class field, one that will be visible in other methods. This way you can call pl.stop() (or whatever method is needed) elsewhere if you want to stop the sound.

Note that I'm not familiar with the PlaySound class and so cannot make specific recommendations about it.


As an aside, your code looks like Swing code, and if so, you will want to play your sound on a thread that is background to the GUI. Otherwise you risk locking your GUI while the sound is playing.

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