2

Recently, I've been experimenting with mixing AudioInputStreams together. After reading this post, or more importantly Jason Olson's answer, I came up with this code:

private static AudioInputStream mixAudio(ArrayList audio) throws IOException{
    ArrayList<byte[]> byteArrays = new ArrayList();
    long size = 0;
    int pos = 0;
    for(int i = 0; i < audio.size(); i++){
        AudioInputStream temp = (AudioInputStream) audio.get(i);
        byteArrays.add(convertStream(temp));
        if(size < temp.getFrameLength()){
            size = temp.getFrameLength();
            pos = i;
        }
    }

    byte[] compiledStream = new byte[byteArrays.get(pos).length];
    for(int i = 0; i < compiledStream.length; i++){
        int byteSum = 0;
        for(int j = 0; j < byteArrays.size(); j++){
            try{
                byteSum += byteArrays.get(j)[i];
            }catch(Exception e){
                byteArrays.remove(j);
            }
        }
        compiledStream[i] = (byte) (byteSum / byteArrays.size());
    }

    return new AudioInputStream(new ByteArrayInputStream(compiledStream), ((AudioInputStream)audio.get(pos)).getFormat(), ((AudioInputStream)audio.get(pos)).getFrameLength());
}

private static byte[] convertStream(AudioInputStream stream) throws IOException{
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int numRead;

    while((numRead = stream.read(buffer)) != -1){
        byteStream.write(buffer, 0, numRead);
    }

    return byteStream.toByteArray();
}

This code works very well for mixing audio files. However, it seems the more audio files being mixed, the more white noise that appears in the returned AudioInputStream. All of the files being combined are identical when it comes to formatting. If anyone has any suggestions\advice, thanks in advance.

Community
  • 1
  • 1
Pojo226
  • 45
  • 1
  • 5
  • *"If anyone has any suggestions\advice,.."* Post an [SSCCE](http://pscode.org/sscce.html). Either hot-link to some small sounds, or generate them in code. *"..thanks in advance."* You're welcome. – Andrew Thompson Jun 21 '11 at 15:23

1 Answers1

0

I could be wrong, but I think your problem has to do with the fact that you are messing with the bytes instead of what the bytes mean. For instance, if you are working with a 16 bit sampling rate, 2 bytes form the number that corresponds to the amplitude rather than just 1 byte. So, you end up getting something close but not quite right.

gvd
  • 16
  • I know this is a long dead post, but for anyone who comes across it: gvd was right in that I was going about the problem wrong. Since then I learned more about digital audio, reading up on audio analog to digital conversion is a great starting place for anyone else curious about this. – Pojo226 Oct 08 '13 at 18:47