05 May 2007

Mixing two audio files using Java Sound

There are no special methods in the Java Sound API to do this. However, mixing is a trivial signal processing task, it can be accomplished with plain Java code .
So manually mixing the two or more audioinputstreams using some attitional api
note: each Audiofile length must be same

Download the Sample Sourcecode with API : Sample Source code ais_mixer.rar
Alternate Downloading Mirror :mirror(ais_mixer.rar)

or


Example:

first convert audiofile to audioinputstream

audioInputStream = AudioSystem.getAudioInputStream(soundFile);
audioInputStream2 = AudioSystem.getAudioInputStream(soundFile2);

Create one collection list object using arraylist then add all audioinputstream's

Collection list=new ArrayList();
list.add(audioInputStream2);
list.add(audioInputStream);

then pass the audioformat and collection list to MixingAudioInputStream constructor

MixingAudioInputStream mixer=new MixingAudioInputStream(audioFormat, list);

finaly read data from mixed audioninputstream and give it to sourcedataline

nBytesRead =mixer.read(abData, 0,abData.length);

int nBytesWritten = line.write(abData, 0, nBytesRead);

5 comments:

pnk087 said...

Hi,

I have tried this tool and here is what I found:

In this call:
nBytesRead =mixer.read(abData, 0,abData.length);

the nBytesRead always return the same value (128000) so the loop:
while (nBytesRead != -1) {}
will never stop.
Please review.

pnk087 said...

BTW, could you give more explanation in detail of MixingAudioInputStream.read(byte[] abData, int nOffset, int nLength) method. It's hard for me to understand about what this method does.
Thanks

Anonymous said...

The host doesn't have this file anymore, or I can't access it, I get a 403 forbidden, and your mirror only has 2 other files I don't need. Could you reupload it, or post it, or mirror it? Thanks.

Anonymous said...

The host doesn't have this file anymore. Please, publish the file again.

Anonymous said...

isn't javax.sound.sampled.Mixer capable of doing this? i'm trying to figure out how to mix two audio streams right now ... creating a multiplexed stream is not whati want, i want to take the tracks in the input streams, and create a single track on the output ... sigh, hopefully i'll come across an example, not clear to me yet from the docs. the Java Advanced Sound mixer i got from AudioSystem doesn't seem to have any target lines ... i must be doing something wrong =)