Simple to use sound in Java games

I’m just an amateur games writer but I’d like to know an easy to use way of playing sound in games. I’m looking for something that’s:

  • easy of use (most important)
  • good performance (important)
  • the ability to play mp3’s (preferably)
  • volume control (preferably)
  • left right control (a nice to have).

When running my current game on a low performance laptop (haswell 2955U, 2GB, no GPU) I find the game itself play fine but the sound is all over the place and eventually seems to turn off. I’m not sure whether this is a caching thing (currently use wav’s sized between 20k and 100k) or whether it’s just too much processing to play the sound as well as the game.

I run the game as a jar and my existing sound code is a bit like this:

SoundEffect.SHOOT.play();

enum SoundEffect {
		ALIEN_HIT("alien_hit"),
                ....
		SHOOT("machine_gun");

	// Each sound effect has its own clip, loaded with its own sound file.
	private Clip clip;
	private String name;
	private long timeLastSound = System.currentTimeMillis();

	// Constructor to construct each element of the enum with its own sound file.
	SoundEffect(String file) {
		try {   
			// play sound
			name = file;
			AudioInputStream inputStream = AudioSystem.getAudioInputStream(this.getClass().getResource(file+".wav"));
			AudioFormat format = inputStream.getFormat();
			DataLine.Info info = new DataLine.Info(Clip.class, format);
			clip = (Clip)AudioSystem.getLine(info);
			clip.open(inputStream);

		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}

	public void stop() {
		if (clip.isRunning()) { clip.stop(); }
	}

	// Play or Re-play the sound effect from the beginning, by rewinding.
	public void play() {
		timeLastSound = System.currentTimeMillis();

		// Stop the player if it is still running
		if (clip.isRunning()) { clip.stop(); }

		// play
		clip.setFramePosition(0); // rewind to the beginning
		clip.start();     // Start playing
	}

	static void init() {
		values();
	}
}

Suggestions for a simple to use method of making sounds or how to speed up what I have? would switching to mp3’s help or would I just be trading file size for processing required?

Many thanks

Mike

My usual recommendation is TinySound, see if it offers the functionality and performance you need.
I also suggest using Ogg Vorbis instead of MP3. The only performance impact of using compressed formats is at load time if the sound isn’t streamed.

I have a usage example for TS: http://www.java-gaming.org/topics/getting-tinysound-to-play-oggs-in-a-jar/36100/msg/342436/view.html#msg342436

Many thanks, I’ll try that library out.

[quote=“BurntPizza,post:2,topic:55519”]
Can I ask why?

One, TinySound supports it, but afaik the java runtime doesn’t support MP3 by default, and making it work is finicky.

Second, MP3 is a proprietary format and patent encumbered, see this FAQ: http://mp3licensing.com/help/developers.html
So if you ever want to sell your game, you’ll have to buy a license (but only if it sells 5000 or more copies… tricky, tricky). You also have to buy a new license for each game using MP3.

Vorbis and related formats on the other hand are all open source, free software.

EDIT: more detailed comparison between the two: https://www.wikivs.com/wiki/MP3_vs_Ogg_Vorbis

Thanks for all the info.
I suspect I’ll never sell 5000 games though :’(

I advise you to use Paul Lamb’s Sound library with its JOAL plugin and its Ogg codec. At first, Paul Lamb’s sound library is easy to use, very stable, efficient (you can use streaming or keep everything in memory) and quite famous (it’s used in Minecraft). Secondly, its JOAL plugin allows to benefit of OpenAL-Soft which is an excellent fallback where there is no OpenAL hardware implementation. Thirdly, I don’t really see the interest of using MP3 over OGG. Finally, as OpenAL-Soft works correctly, you don’t need a fallback on Java Sound, you won’t have any problem on JVMs in which it doesn’t work correctly for various reasons and you can use it with a compact profile (since Java 1.8) with a few changes. I remind that there is still this nasty bug on extremely short sounds, there is a workaround but it’s annoying to have to add a few seconds of data into each file :s

In my humble opinion, you can use it under Android too if you remove the midi support and if you replace javax.sound.sampled.AudioFormat by a dummy class to store the very few fields really used by Paul Lamb Sound Library.

Unfortunately, TinySound heavily relies on Java Sound, it doesn’t support OpenAL and it can’t work on Android. As it stores all audio as 16-bit, 44.1kHz, 2-channel, linear PCM data, if there is no supported mixer on a computer for these settings, the end user won’t hear anything.

Well, personally I disagree with you, but the one thing I’d question -

[quote=“gouessej,post:6,topic:55519”]
Are you seriously saying you’ve found a device that doesn’t support CD format audio?! :o

I don’t think that many end users will have the patience to fix the problems with their OS to make Java Sound work correctly anew.

I have found no such device but I can find a device whose “best” Java Sound mixer claims not to support this audio format. That’s one of the reasons that forced me to abandon Java Sound.

Neither do I, but then if you use a library that actually does JavaSound right then that won’t be an issue! (that incidentally does not include Paul’s library unless it’s been rewritten since I last looked at it)

You still on about that damn webcam?! :stuck_out_tongue: There used to be issues on Linux due to deprecated use of ALSA (and a bug in ALSA). There’s a whole new JavaSound implementation for Linux these days.

I haven’t used external libraries in Java for anything. I figured I’d start with the TinySound option because it said it was easy to use and that always counts for a lot in my book.

I tried pulling the TinySound jar’s but can’t seem to work out how to actually set things up so I can use them. I understand about calling TinySound.init() etc. It’s just working out how to include TinySound within my own program. Could someone explain (using really simple words) what I need to do. I’m on Win10 and just call javac from the command line.

Many thanks

Mike

OpenAL-Soft seems to work better than JavaSound, what’s the point of using the latter except the fear of using a third party library? Just add jogamp-fat.jar into your classpath and you benefit of JOGL, JOAL and JOCL without headaches and/or tinkering the Java library path.

mike_bike_kite, read the “man”, use the -cp option to add a JAR into your classpath.

I’m using libGDX which uses OpenAL as backend. Works great. The advantage is, that with the libGDX frontend, you can stay compatible with other platforms.

LWJGL also comes with an OpenAL wrapper. I don’t like the API, but there are good tutorials and it works fine.

Paul Lamb Sound Library has a backend based on this library too. A contributor is currently porting it to its third version.

Lots, because I actually understand the difference. OpenAL-Soft is an audio library that builds on top of various native audio backends. JavaSound is a low-level API that abstracts those native audio backends. I’m not in any way suggesting people don’t use third-party libraries, whether OpenAL or TinySound or something else. Leave library writers to deal with the low-level stuff. JavaSound generally works fine when the library authors have actually read and understood the spec, just like the OpenAL-Soft authors have to understand the specs of the various low-level libraries they use.

Or in other words, use the library that best suits your application. If OpenAL gives you what you need, use it. If something else does, use that.

btw Julien, have you actually ever tried TinySound or are you basing your opinion on other libraries that weren’t well written? I’ve not used it myself (I have my own library), but various people around here seem to like it.

I spend a lot of time in reading the source code of numerous libraries including TinySound. By the way, I’m currently planning to read the whole source code of WildMagic Engine 5.13 by David H. Eberly. I found the source code of Paul Lamb’s Sound Library a bit weird, I advised him to use a simpler class to store the data about the audio format. Actually, I would like him to put his source code into a repository so that I can contribute more easily. I looked at the source code of TinySound to be sure that it uses JavaSound, I looked at how it uses this API.