Reputation: 1505
I've recently finished a small game and have been trying to add audio to it. Currently the sound system I have is working (basically the same code as the top answer here ), but there is a significant stall during every output (~200-300 ms). Since it's a quick game I'm looking for something significant quicker. I'm not experienced with Threads, but would those be applicable here?
Upvotes: 2
Views: 169
Reputation: 1505
As much as I'd like to accept one of these existing answers, I solved my problem in a simple way. By loading all the referenced File
variables during initialization, the delay does not come back at any point during gameplay. However if this is not an adequate solution for anyone else viewing this question, I would also recommend Vulcan's answer.
Upvotes: 0
Reputation: 28687
Instead of reading the file every time you wish to play its contents in audio format, read the file once into a byte array and then read the audio from that array of bytes.
public static byte[] getBytes(String file) {
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte[] bytes = new byte[(int) raf.length()];
raf.read(bytes);
return bytes;
}
Then, you could simply alter the playSound
method to take a byte array as the parameter, and then write them to the SourceDataLine
instance to play the sound (like is done in the original method, but it reads them from the file just before it writes them).
Upvotes: 3
Reputation: 13529
The call to drain
is a blocking one and it causes the delays that you observe. You do not need to wait there. However, if you let the sound output operate in parallel with your other code, you should also define what happens if there is a lot of sound in your sound buffers and you are queueing more. Learn about the available
method and the rest of the API to be able to manage the sound card flexibly and without any "lagging sound" effects.
Threads can also be used for this purpose, but it is not necessary here. The role of the parallel process can be adequately played by the sound driver itself and the single threaded approach will make your application easier to design and easier to debug.
Upvotes: 0
Reputation: 8534
You could try passing a BufferedInputStream to the overloaded method AudioSystem.getAudioInputStream() instead of passing a File.
Upvotes: 0