Java playing the same audio over the another one

I am making a game which has mouse over sound in the menu. However the 2nd time when the sound is played and the first one didn’t finished yet the 2nd cuts the first. Is there any way to fix that issue?

public static AudioClip menuMouseOver; //creating the audioClip
menuMouseOver = Applet.newAudioClip(new File(soundsLocation+"\menuMouseOver.wav").toURL()); //loading the sound into the audioClip
menuMouseOver.play(); //calling the audioClip to play.

Answer

AudioClip, Clip, SourceDataLine are not set up for concurrent playback. It is possible to create multiple AudioClips or Clips from a common .wav file, and Java’s audio system will mix these together. In this case, though, you have to hold multiple copies of the audio in memory, and audio is pretty bulky.

But coding concurrent playbacks of a single audio file is not particularly tricky. A relatively straight-forward plan is to load a single copy of the file in memory, and then create and manage multiple “cursors” that index into this memory area for your playback. The audio data from each “cursor” can be added together and output via a SourceDataLine.

This is the plan I used for AudioCue, which is meant to be a sort of super Clip, allowing real time volume, panning and pitch changes as well as concurrent playback. I believe TinySound is another audio library that enables concurrent playback.

Leave a Reply

Your email address will not be published. Required fields are marked *