resample audio buffer from 44100 to 16000

前端 未结 5 391
不思量自难忘°
不思量自难忘° 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:46

    You can use an OfflineAudioContext to do the resampling, but you need to convert your data-uri to an ArrayBuffer first. This solution works in the browser, not on the server, as it's better to send lower quality audio (lower sample rate) on the network, than send a lot of data and resample on the server.

    // `source` is an AudioBuffer instance of the source audio
    // at the original sample rate.
    
    var TARGET_SAMPLE_RATE = 16000;
    
    var offlineCtx = new OfflineAudioContext(source.numberOfChannels,
                                             source.duration * TARGET_SAMPLE_RATE,
                                             TARGET_SAMPLE_RATE);
    
    // Play it from the beginning.
    var offlineSource = offlineCtx.createBufferSource();
    offlineSource.buffer = source;
    offlineSource.connect(offlineCtx.destination);
    offlineSource.start();
    offlineCtx.startRendering().then((resampled) => {
      // `resampled` contains an AudioBuffer resampled at 16000Hz.
      // use resampled.getChannelData(x) to get an Float32Array for channel x.
    });
    

提交回复
热议问题