resample audio buffer from 44100 to 16000

前端 未结 5 456
不思量自难忘°
不思量自难忘° 2021-02-04 09:56

I have audio data in format of data-uri, then I converted this data-uri into a buffer now I need this buffer data in new samplerate, currently audio data is in 44.1khz and I nee

5条回答
  •  不要未来只要你来
    2021-02-04 10:54

    No answers are correct. Here is the perfect code.

    // `sourceAudioBuffer` is an AudioBuffer instance of the source audio
    // at the original sample rate.
    const DESIRED_SAMPLE_RATE = 16000;
    const offlineCtx = new OfflineAudioContext(sourceAudioBuffer.numberOfChannels, sourceAudioBuffer.duration * DESIRED_SAMPLE_RATE, DESIRED_SAMPLE_RATE);
    const cloneBuffer = offlineCtx.createBuffer(sourceAudioBuffer.numberOfChannels, sourceAudioBuffer.length, sourceAudioBuffer.sampleRate);
    // Copy the source data into the offline AudioBuffer
    for (let channel = 0; channel < sourceAudioBuffer.numberOfChannels; channel++) {
        cloneBuffer.copyToChannel(sourceAudioBuffer.getChannelData(channel), channel);
    }
    // Play it from the beginning.
    const source = offlineCtx.createBufferSource();
    source.buffer = cloneBuffer;
    source.connect(offlineCtx.destination);
    offlineCtx.oncomplete = function(e) {
      // `resampledAudioBuffer` contains an AudioBuffer resampled at 16000Hz.
      // use resampled.getChannelData(x) to get an Float32Array for channel x.
      const resampledAudioBuffer = e.renderedBuffer;
    }
    offlineCtx.startRendering();
    source.start(0);
    

提交回复
热议问题