Playing small sounds in Java game

Zarkonnen picture Zarkonnen · Oct 28, 2008 · Viewed 7.4k times · Source

For the computer game I'm making, I obviously want to play sound. So far, I've been using AudioClip to play WAV files. While this approach works fine, the WAV files tend to be gigantic. A few seconds of sound end up being hundreds of kB. I'm faced with having a game download that's 95% audio!

The obvious option here would be to use MP3 or Ogg Vorbis. But I've had limited success with this - I can play MP3 using JLayer (but it plays in the same thread). As for Ogg, I've had no luck at all. Worse, JLayer's legal status is a bit on the dubious side.

So my question is to both Java developers and generally people who actually know something about sound: What do I do? Can I somehow "trim the fat" off my WAVs? Is there some way of playing Ogg in Java? Is there some other sound format I should use instead?

Answer

akarnokd picture akarnokd · Jun 12, 2009

You could use JOrbis library to play back OGG music. For working sample usage you can look at these files here.

I also experimented with some lossless audio compression, for example I had a 16 bit mono sound. I separated the upper and lower bytes of each sample and put them after each other. Then I applied a differential replacement where each byte is replaced by its difference from the last byte. And finally used GZIP to compress the data. I was able to reduce the data size to 50-60% of the original size. Unfortunately this was not enough so I turned to the OGG format.

One thing I noticed with 8 bit music is that if I change the audio volume, the playback becomes very noisy. I solved this problem by upsampling the audio data to 16 bit right before the SourceDataLine.write().