Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing small sounds in Java game

Tags:

java

audio

mp3

ogg

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?

like image 542
Zarkonnen Avatar asked Oct 28 '08 18:10

Zarkonnen


People also ask

Can you play sounds in Java?

The Java Sound APIs are designed to play sounds smoothly and continuously, even very long sounds. As part of this tutorial, we'll play an audio file using Clip and SourceDataLine Sound APIs provided by Java. We'll also play different audio format files.

How do you add music to a game in Java?

BGM = new AudioStream(new FileInputStream("music. wav")); BGM = new AudioStream(new FileInputStream("/music. wav")); BGM = new AudioStream(new FileInputStream("music")); BGM = new AudioStream(new FileInputStream("all the url path at my computer.

How do you add sound effects in HTML?

HTML Audio - How It WorksThe controls attribute adds audio controls, like play, pause, and volume. The <source> element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.


2 Answers

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().

like image 55
akarnokd Avatar answered Sep 19 '22 16:09

akarnokd


These may be outdated, but they are officially recognized by the Xiph.org team (who maintain Ogg and Vorbis, among others). http://www.vorbis.com/software/#java

like image 21
sep332 Avatar answered Sep 19 '22 16:09

sep332