开发者

Java - Mixing audio files generates unwanted white noise

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];
            }c开发者_Go百科atch(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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜