Looking for a way to control sound volume and panning

1.6k Views Asked by At

I've been creating a Java project where I'd like to have multiple sounds playing at once, and how to control each sound's volume and panning. I've Googled around and read about 3 different ways; the thing is, I can't seem to find any tutorials or examples of how to use them. They are:

 import java.applet.AudioClip;
 import javax.sound.sampled;
 import sun.audio.SomethingOrOther; // Sorry, don't recall off-hand.  It was an "un-documented" site

As I continued to read, I found out that AudioClip was only for a certain kind of applciation ("applet"?) and the third one was only mentioned on one of a hundred sites. The second one was brought up on this site, but it dealt with a different topic altogether (something about "lines"). Anyway, I'm familiar enough with Java syntax to get the idea, but I haven't been able to find anything presented in a straight-forward way; so if anyone could point me in the right direction on this it would be greatly appreciated.

2

There are 2 best solutions below

0
On

Take a look at this trail in the Java tutorials: Trail: Sound, specifically Processing Audio with Controls

As suggested in Andrews comment you should look at FloatControl.Type (PAN for example).

0
On

It seems to me the only real option for stereo mixing is to access the sound data at the frame (i.e., per sample) level. The built-in controls for pan and volume and such are kind of dubious, and having multiple SourceDataLines all executing concurrently won't even work on some OS's (some Linux).

To do so, there are two options: write your own or use a library.

The Java Tutorials "Trail:Sound" lightly mentions the direct manipulation option at the end of the tutorial on "Controls". The explanations they give ARE helpful for figuring out how to access the individual sound frames. It is a big job learning this stuff if you are coming into it for the first time (and it sounds like you are, if you are using AudioClips).

I suspect the best option for you will be to use a library such as TinySound. You can read more about it at Java-Gaming.org Another library to investigate is JAudioLibs.

I'm writing my own stereo mixer for game coding, and have implemented a rough-and-ready ability to control the volume and panning. In doing so, I discovered that Java does not give any real-time guarantees other than that it will try to keep the output sound continuous. Things like garbage collection, thread-slicing, playing from byte-code vs memory, all these things work against real-time consistency. See this article for more gory details: REAL-TIME, LOW LATENCY AUDIO PROCESSING IN JAVA.

On the plus side, Java's core implementation (e.g., things like AudioInputStream and SourceDataLine) are very powerful, and it is possible to do a LOT of real-time processing. But it takes some careful coding.