Reputation: 25
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.
Upvotes: 2
Views: 364
Reputation: 285403
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.
Upvotes: 1