ultraabox / ultrabox_typescript

ultrabox source code
MIT License
35 stars 25 forks source link

Downmix custom samples to mono #72

Open leovoel opened 1 year ago

leovoel commented 1 year ago

When we first got this working I left this comment in the code:

https://github.com/ultraabox/ultrabox_typescript/blob/63f0be5f890b1d5a66ffc6cd350b42ab8f17957f/synth/SynthConfig.ts#L333-L334

The downmixing code should probably be something like this:

const length: number = audioBuffer.length;
let data: number[] = [];
// https://www.w3.org/TR/webaudio/#down-mix
switch (audioBuffer.numberOfChannels) {
    case 1: {
    // Mono
    data = Array.from(audioBuffer.getChannelData(0));
    } break;
    case 2: {
    // Stereo
    const l: Float32Array = audioBuffer.getChannelData(0);
    const r: Float32Array = audioBuffer.getChannelData(1);
    for (let i: number = 0; i < length; i++) data.push((l[i] + r[i]) * 0.5);
    } break;
    case 4: {
    // Quad
    const l: Float32Array = audioBuffer.getChannelData(0);
    const r: Float32Array = audioBuffer.getChannelData(1);
    const sl: Float32Array = audioBuffer.getChannelData(2);
    const sr: Float32Array = audioBuffer.getChannelData(3);
    for (let i: number = 0; i < length; i++)
        data.push((l[i] + r[i] + sl[i] + sr[i]) * 0.25);
    } break;
    case 6: {
    // 5.1
    const l: Float32Array = audioBuffer.getChannelData(0);
    const r: Float32Array = audioBuffer.getChannelData(1);
    const c: Float32Array = audioBuffer.getChannelData(2);
    const sl: Float32Array = audioBuffer.getChannelData(4);
    const sr: Float32Array = audioBuffer.getChannelData(5);
    for (let i: number = 0; i < length; i++) data.push(
        Math.SQRT1_2 * (l[i] + r[i]) + c[i] + 0.5 * (sl[i] + sr[i])
    );
    } break;
}

It may be a good idea to figure out how to use ChannelMergerNode instead of doing this manually.

MainCharacteroftheProblem commented 1 year ago

It might be useful to add an option to the sample importer to auto-split stereo files into two separate mono chip waves

leovoel commented 1 year ago

Yeah probably. That would need #66 for it to work nicely, I think.