I am making an game and when a player attacks, I want to play a sound. I am stuck trying to pause the key listener while the sound is being played. This is what I want to do…
if player attacks, play sound,
if a key is pressed check if sound is playing, if not then execute…
… but I can’t find any methods to check if the sound is playing. I tried just pausing the thread for the length of the sound but it doesn’t pause the key listener and just seems like poor coding.
I am using AudioClip to load and play the sound.
Any advice would be greatly appreciated.
quote from: http://www.onjava.com/pub/a/onjava/excerpt/jenut3_ch17/index.html
[quote] But this highlights one of the shortcomings of the AudioClip interface: it allows you to play( ), stop( ), or loop( ) a sound, but it provides no way to track the progress of the sound or find out when it has finished playing. To achieve that level of control over the playback of sound, we need to use the JavaSound API, which we’ll consider in the next section.
[/quote]
so as soon as I saw that I stopped, you can find the answer there…
KeyListener may be replaced by a KeyEventDispatcher used in common with the currentKeyboardEventDispatcher that you can find in the KeyboardFocusManager static method getCurrentKeyboardFocusManager() . Thus you will be able to make the manager to pause for a while because the Thread is single when it calls back the registered dispatchers. I use it though I’m having problems to get it synchronized with the whole stuff for the moment…
still, it doesn’t solve his major problem… and that is to cleanly learn is a certain sound playing or not. I think it’s better to focus on that then doing workarounds. Funkymonk, if you pause keylistener thread then it will be unresponsive for other actions also, and you will be stuck with one action until sound stops playing.
well that’s a bit fuzzy to pause the keyboard… My method involves launching swing timers and reading from one synchronized Stack of KeyEvents caught by the dispatcher, that avoids “pausing” the dispatcher.
Moreover about the audio, it’d be “thinkable” to use Thread-locking on your sound clip launched from dispatcher while it is playing. Of course the problem is to monitor the sound target, which is unknown to me.
I’m using javax.sound.sampled.Clip and use it’s isActive() method to check if the sound is playing.