Sound in Java

Hi all,

I have looked around for information on this subject and it seems to be…

a.Outdated.
b.Confusing and ill explained.

If someone could please give me a loose explanation on this subject orjust point me in the right direction of reading materials I would be grateful.

Christopher.

Look into slick2d, or slick-util. Both do sound very easily.

These are awesome. They also in turn led me to Tiled…

There goes another 10,000 hours of my life.

Paul Lamb Sound Library is just fine :slight_smile:

Yeah, I am on my third pass through the Java Tutorials section on Sound, just the “.sampled” section. I think I’m starting to make some headway. http://download.oracle.com/javase/tutorial/sound/index.html

If you do decide to try writing raw Java audio, I recommend making sure you give the section “Using Files and Format Converters” a look. For no apparent reason, this section has the best example code. Right where you expect it! Several sections AFTER where it should be! :cranky:

These guys have some useful information posted:
http://jsresources.org/
There’s a pretty great FAQ section.

StackOverFlow has some interesting java sound questions come up now and then. So does Java-Gaming.org!http://www.java-gaming.org/index.php/board,16.0.html

Java Sound is quite powerful, actually. But with power comes responsibility…you need to be pretty solid with threads & file i/o, for starters.

I knew you would be one of the few keen to talk audio!

You have had success playing .ogg files yes?

I just want to start there…
Create a class, choose a file, play it… speakers start moving.

Then I can hopefully start working through the more complex stuff.

Dragging my feet. No excuses.
Best ogg-related tutorial I found:
http://www.jcraft.com/jorbis/tutorial/Tutorial.html
If you search, you will find examples of playing back a .wav in java.

I don’t know that there is a “just do it” way with Java Sound. It is powerful, designed more for tool-making than “simple” playback for application-level developers. Also, it is free so there is less support than there would be if you forked over $500 for a solution.

You will have to either dive in or go for one of the other solutions offerred. Do look at the code in the section on format conversions. It seems illogical that there would be the most concrete code examples, under a heading that sounds complex, but they are truly helpful.

You could go two ways here.

  1. Easy way, just play the sound straight through or loop. No control over where to start, pause, or volume:

java.applet.AudioClip clip = java.applet.Applet.newAudioClip(new URL("url/to/file.wav"));
clip.play();
clip.loop();
clip.stop();

  1. The complicated but fast to learn way, javax.sound.sampled package:

AudioInputStream audio = AudioSystem.getAudioInputStream(new URL("url/to/file.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
clip.loop(5);
clip.stop();
clip.setMicrosecondPosition(123456789L);
clip.start();
//etc...

Of course there are many different overloaded methods in AudioSystem and other classes that allow complete control over the output.

Hope that helps :slight_smile:

Ok,

I finally got some audio playback from java!
It was a tearful moment to say the least.

My problem was I was trying to play back a 24bit file. Once i tried playback with a 16bit It returned some audio.
The audio I am hearing however sounds like it is being bit crushed down to 8bit audio… Is there a a way to set bitrate playback?

This is also only with AIF and WAV files. I have still had no luck getting OGG playback, the program still crashes as I was experiencing before.

Thanks in advance.
Christopher.

Hmmm actually…

It doesnt sound bitcrushed it sounds plain shit. Perhaps a streaming problem… I am missing something…

I gave up on Java Audio after reliably getting segmentation faults when following the API (and apparently the bug I experienced, was fixed many version ago).

I’ve been using LWJGL for audio since, with little to no problems. It might take some time to learn, but should be worth it.
I use VorbisSPI for ogg-vorbis support, which adds around 25 lines of extra code (compared to using just wave).

  • Scarzzurs

I have been using Slick2d which apparently makes the code as simple as…

Sound fx = null;
fx = new Sound(“testdata/testloop.ogg”);
fx.loop();

this does achieve playback, albeit, the horribly distorted one…
Does lwjgl have a wiki with decent tutorials like slick… at this point I just want to get normal audio coming out my speakers as I am concerned I am missing something…

FIXED

If you would like to have streaming audio with only a few commands I recommend reading the following code/guide…
http://lwjgl.org/wiki/index.php?title=Slick-Util_Library_-Part_2-_Loading_Sounds_for_LWJGL

In order for this code to run you will need the following in your build path,

lwjgl.jar
slick.jar
jogg(current version number).jar
jorbis(current version number).jar

These can be downloaded here for lwjgl,
http://lwjgl.org/download.php

and here for Slick and the other Jars,
http://slick.cokeandcode.com/

For information on how to add these to your build path see here…
http://www.cs.bsu.edu/homepages/pvg/misc/slick_eclipse_tutorial.php

Just do the same for the jogg, jorbis jars, which will be located in the slick2d libs folder.

Ogg files are recommended because of the their minimal file size yet quality compression, a good converter for mac can be found here…

Hopefully this helps someone avoid the pain of java sound.

Java Sound isn’t that painful. It’s powerful and useful, no need for external libraries.

Hi Christopher - I appreciate the references you listed! Will check them out at some point, hopefully sooner than later.

My experience with .wav’s is limited. I can export my sounds to .wav’s via Cakewalk’s “Sonar” app. But they only play back, on my computer, via Windows built-in media player, if the sample size is 16 bits. So it doesn’t surprise me if you had 24-bit encoding and were unable to do playback.

Stuff that I have exported to 16-bit wavs plays back with great fidelity. I’m curious if you ever looked at the section on converting formats as I suggested. There is info there about how to set files from one type to another. Also, to query the “AudioSystem” to see if you have an output line that supports the type of sound file you are hoping to play back. Did you try this approach at all? Just curious.

I just wrote a routine that converts wav data, stereo 16-bit, 44100, little endian byte arrays to float arrays (-1.0 to 0.9999). Next step, to convert them back for playback…

Don’t worry I’m just being dramatic. Like all noobies i want less code more action. I was so frustrated the other day that if the Java Sound API were a person i would have kicked them in the teeth.

Turns out I wasn’t doing a simple check to see if the music was playing before making the request. This sends numerous continuous requests to stream the sound file and as a result creates the illusion of poor quality audio.


if(!music.playing()){
        	music.play();
		}

Noobie mistake.

I went over this again just now and It made a lot more sense this time around. My silence filled speakers were a bit a distraction when i passed over it before. Strange how this section is several sections down when it is the most relevant information. I already had a basic understanding that this is how java handled audio based on working with DAW,s. I definitely want to go down the path you have taken too with converting to code.

Apparently this is even more compact and quicker to load?
Also you will be able to protect your game music this way yes? otherwise the user will have a nice fat data directory full of your handcrafted compositions…?

Thanks for the reply! Agreed, I’ve had to take multiple passes on the Java Audio documentation and I really don’t understand why the best example code is so far back.

The point of using a floats array is that this is a good data representation for DSP. I think it is pretty much standard, like using unit vectors. I don’t know that anything is saved in terms of memory or RAM or speed. A single float requires several bytes, and you are still using 44100 frames per second, presumably. A friend has a “stretching” algorithm that I want to try, but it assumes a float array.

(My task today, if I get time this evening, is to take my float array and convert it back to a wav for playback. Have to make a .wav FileFormat, attach it to a SourceDataLine that supports wav playback, yada yada. We’ll get to the stretching part later.)

About protecting composition, I’m not sure what to say. If you have a good ear, you can pretty much pick apart (transcribe) anything. And of course, you can direct a sound stream into a DAW. With a book, every word is there. With a painting or film, all the visuals are right there in the open. Software is also possible to decompile, as witnessed by several threads on this site, including a rather humorous one in which one of my own bright attempts at a Captcha Applet was decompiled. (Within hours of posting, Markus Persson & Dzzd had pretty much shredded it to pieces.)
http://www.java-gaming.org/index.php/topic,23389.0.html

If you embed your mp3’s or ogg’s or wav’s or whatever as a resource, I’m sure it can be decompiled. But what else is there? It’s too slow/unreliable to stream (except for maybe some very special cases where it could work…), so audio content should be delivered with the game, I think. I suppose one could make some sort of scrambler and include that as a layer. But the code for the descrambling would also be easy to decompile and redo. Costs/benefits.

Another thought: I’ll put off worry about theft until it becomes apparent someone likes something enough to actually steal it.

Wow! have to let me know if you get playback happening and whether the stretching algorithm works. The one in ableton live blows my mind. It auto warps loops to your current tempo and then you can just drag and stretch transients as if they were physically tangible. This in combination with stretching methods such as beat preservation, pitch preservation etc.

The example you posted with the captcha gave me a good laugh, thanks for sharing.

If someone can build it, someone can un-build it. Its not that I want to keep the entire world out of the files and music I write, just the general population. Even if you were a paying customer, if a game you downloaded came with a folder labeled “soundtrack” it would be hard to justify buying a soundtrack for that game if it were offered as a product. I mean not that much is to garnered from online music sales these days.

All this assumes however, that users would like my music so much that they would want to steal/hack/download it…

“Don’t worry about people stealing an idea. If it’s original, you’ll have to jam it down their throats.” – Howard Aiken

Ableton sounds like a fantastic tool.

Meanwhile, back at the cave site for recreating stone wheels, we have achieved playback of a wav previously loaded into an array of floats. Nothing more, as of yet.

Edit: added a “play backwards” button. It can now load wave files and play them backwards. Fidelity is pretty fine, as far as I can tell. I’ve got OK studio monitors.

Spent too much time tracking down a stoopid bug in a for loop (I’m not used to decrementing). :stuck_out_tongue: