Modify AudioBuffer volume in JavaScript

286 views Asked by At

How can modify AudioBuffer volume in javascript ? I just wanna modify AudioBuffer volume without play any sound and without use any gain. Finally , I wanna to have a new AudioBuffer with modified volume.

1

There are 1 answers

0
chrisguttandin On BEST ANSWER

Let's say you want to multiply all values within an existing AudioBuffer by 2. You could do that by looping over all values to apply the computation.

for (let channel = 0; channel < audioBuffer.numberOfChannels; channel += 1) {
    const channelData = audioBuffer.getChannelData(channel);

    for (let sample = 0; sample < channelData.length; sample += 1) {
        channelData[sample] *= 2;
    }
}

This will edit all values in place. If you want to copy all values to a new AudioBuffer instead you can do it as follows.

const copiedAudioBuffer = new AudioBuffer({
    length: audioBuffer.length,
    numberOfChannels: audioBuffer.numberOfChannels,
    sampleRate: audioBuffer.sampleRate
});

for (let channel = 0; channel < audioBuffer.numberOfChannels; channel += 1) {
    const channelData = audioBuffer.getChannelData(channel);
    const copiedChannelData = copiedAudioBuffer.getChannelData(channel);

    for (let sample = 0; sample < channelData.length; sample += 1) {
        copiedChannelData[sample] = channelData[sample] * 2;
    }
}

The example above creates an AudioBuffer with the exact same properties as the existing one. It will leave the existing AudioBuffer untouched.