如何将renderedBuffer保存为音频文件

时间:2016-06-13 16:48:20

标签: javascript audio web-audio web-audio-api

我正在使用web audio api的offlineAudioContext来呈现具有不同播放速度的音频文件。当我这样做时,改变的音频保存在renderedBuffer中。

我想知道如何下载renderedBuffer中保存的音频?

这是我的代码:

// define online and offline audio context
var audioCtx = new AudioContext();
var offlineCtx = new OfflineAudioContext(2,44100*40,44100);
source = offlineCtx.createBufferSource();
// define variables
var pre = document.querySelector('pre');
var myScript = document.querySelector('script');
var play = document.querySelector('.play');
var stop = document.querySelector('.stop');
// use XHR to load an audio track, and
// decodeAudioData to decode it and stick it in a buffer.
// Then we put the buffer into the source
function getData() {
request = new XMLHttpRequest();
request.open('GET', 'sound.mp4', true);
request.responseType = 'arraybuffer';
request.onload = function() {
var audioData = request.response;
audioCtx.decodeAudioData(audioData, function(buffer) {
  myBuffer = buffer;
  source.buffer = myBuffer;
  source.playbackRate.value = 0.50;
  source.connect(offlineCtx.destination);
  source.start();
  //source.loop = true;
  offlineCtx.startRendering().then(function(renderedBuffer) {
    console.log('Rendering completed successfully');
    var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); 
    var song = audioCtx.createBufferSource();
    song.buffer = renderedBuffer;
    song.connect(audioCtx.destination);
    play.onclick = function() {
      song.start();
    }
  }).catch(function(err) {
      console.log('Rendering failed: ' + err);
      // Note: The promise should reject when startRendering is called a second time on an OfflineAudioContext
  });
});
}
request.send();
}
// Run getData to start the process off
getData();
// dump script to pre element
pre.innerHTML = myScript.innerHTML;

0 个答案:

没有答案