Search code examples
javascriptaudioffmpegpcmtyped-arrays

How to merge the raw pcm data of two channels?


I have two Float32Arrays containing the raw pcm data of the left and right channel. Is it possible to create a Float32Array that combines both channel? If so, how would I do that? Can I simply concatenate the arrays?

Cheers!


Solution

  • To merge two PCM files (right and left channels) into one, you need to interleave them:

    (L,1),(R,1),(L,2),(R,2),...,(L,n),(R,n)

    The codes looks something like this:

    const interleavedChannelData = new Float32Array(leftChannelData.length + rightChannelData.length);
    
    for (let i = 0; i < interleavedChannelData.length; i += 1) {
        if (i % 2 === 0) {
            interleavedChannelData[i] = leftChannelData[i / 2];
        } else {
            interleavedChannelData[i] = rightChannelData[(i - 1) / 2];
        }
    }