I’m developing a Java game and want to bundle and play a number of sampled sound effects. I’m planning to use the standard javax.sound.sampled functionality to play them.
What format is best for these kind of samples? I’m looking for a blend of good compression, decent quality and convenience for programmatic use within Java.
Quality vs. Size
Here are some interesting articles on the differences of MP3 vs. WAV.
http://www.angelfire.com/vt2/tommymc3/MP3vsWav.html
http://www.scinet.cc/articles/wma-vs-mp3/wma-mp3.html
http://ask.yahoo.com/20000602.html
Why MP3 and WAV? These are the ones I see most often when creating program, so compatibility is never an issue.
I have this really useful java file that does everything for you. You construct the object with the path to the sound file, then use methods to play, stop, loop it, etc.
In the meantime, you can look at these for reference, albeit they’re not as clean: How can I play sound in Java? .
Simple Programming
Unfortunately, I don’t have the file on this computer, but here’s a simplified version. This doesn’t use javax.swing like you’d hoped, but to be honest, I’ve always preferred alternative methods.
Because this is not the same as the file I have on my other computer, I cannot guarantee MP3 compatibility.
Instantiation:
Now you can call
helloSound.play();whenever you want the clip to be played.I prefer this method so you don’t have to constantly set everything up a stream each time you want to play a clip. This should work effectively with a few sound bites and blurbs, but be sure not to overuse it and take up memory. Use this for common sound effects.
Simple Programming, Cont’d
Found a good file to play MP3s in the same way as I showed above. I completely forgot to put mine in a separate thread, so this is a much better bet.
Easy as pie, right? ;).
Get the jar here. See the documentation here.