How to set up sample rate using web audio API?

人走茶凉 提交于 2019-11-30 09:29:42

问题


I have blob type generated by webaudio API, but the file that is saved have to high sample rate. How can I convert it to lower maybe something like https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext can help? Here is some sample of code:

  var xhr = new XMLHttpRequest();
   /* HERE IS SOME CONVERTATION TO LOWER RATE */

    var fd = new FormData();

    fd.append("randomname", bigBlob);
    xhr.open("POST",url,false);
    xhr.send(fd);

    xhr.onload=function(e) {
        alert(e.target.responseText);
    };

回答1:


  • Create an OfflineAudioContext with the rate you want at the end, and the number of frames there will be at the end
  • Create an AudioBuffer from your raw data buffer
  • Create an AudioBufferSourceNode, set its buffer attribute to the AudioBuffer you just created, and connect this AudioBufferSourceNode to the destination of the OfflineAudioContext
  • Start the AudioBufferSourceNode at 0
  • Start the rendering



回答2:


I couldn't find a way to control the sample rate but here is a way to re-sample (up/down sampling)

function reSample(audioBuffer, targetSampleRate, onComplete) {
    var channel = audioBuffer.numberOfChannels;
    var samples = audioBuffer.length * targetSampleRate / audioBuffer.sampleRate;

    var offlineContext = new OfflineAudioContext(channel, samples, targetSampleRate);
    var bufferSource = offlineContext.createBufferSource();
    bufferSource.buffer = audioBuffer;

    bufferSource.connect(offlineContext.destination);
    bufferSource.start(0);
    offlineContext.startRendering().then(function(renderedBuffer){
        onComplete(renderedBuffer);
    })
}

Extracted from here: https://github.com/notthetup/resampler



来源:https://stackoverflow.com/questions/28821124/how-to-set-up-sample-rate-using-web-audio-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!