How to play Java games?

I successfully play sounds in Java applets (1.5) using the following code:

// get an available clip to play it Clip clip = null; for (Clip clipTemp : players) { if (!clipTemp.isOpen()) { clip = clipTemp; break; } } if (clip == null) { // no available player found, don't play return; } clip.open(audioFormat, audioByteData, 0, audioByteData.length); clip.start(); 

(Players are a list of clips that I open from the very beginning in order to reduce latency, the line listener closes the line when a stop event is received.)

The problem I am facing is intermittent delays of up to 1 second when playing sound. This is pretty bad.

Is there any way to improve this? Should I consider SourceDataLines ?

+2
source share
2 answers

The Java applet translates your clip when you want to play it, so you get a delay because the audio file has not yet been loaded into memory.

It has been a while since I developed the Java applet, but I remember that I used the preload of all my clips, and then subsequent calls to play did not reopen the files.

Here is some code from one of my old projects

 Clip shoot; private loadShootWav() { AudioInputStream sample; sample = AudioSystem.getAudioInputStream(this.getClass().getResource("shoot.wav")); shoot = AudioSystem.getClip(); shoot.open(sample); } public void playShootSFX() { shoot.stop(); shoot.setFramePosition(0); shoot.start(); } 
+2
source

If I read your code correctly, you discover an unopened clip and open it before playing. It would be faster to open open clips and restart them. You may need to stop and reset their positions first, as shown in the JSmyth example in the playShootSFX () example.

I get a pretty good answer with SourceDataLines. The best part is that they start faster than an unopened clip, because they start immediately, and do not wait until ALL data for the sound is loaded into RAM (which happens every time you "open" the clip).

But yes, if you have many sounds that are often played back, a clip pool is the way to go. If you want them to overlap or always play until completion, you need a few copies. If not, stop, reset to 0 and restart. But do not continue the reopening! If you do this, you can also use SourceDataLine.

0
source

All Articles