How to record audio from Audio Element using javascript

4.7k views Asked by At

I am making an audio recorder using HTML5 and Javascript and do not want to include any third party API, I reached at my first step by creating an audio retriever and player using <audio> tag and navigator.webkitGetUserMedia Function which get audio from my microphone and play in through <audio> element but I am not able to get the audio data in an array at this point I don't know what to do which function to use.

1

There are 1 answers

1
mido On

simple just create a audio node, below is tweaked code from MattDiamond's RecorderJS:

function RecordAudio(stream, cfg){

    var config = cfg || {};
    var bufferLen = config.bufferLen || 4096;
    var numChannels = config.numChannels || 2;
    this.context = stream.context;
    var recordBuffers = [];    
    var recording = false;
    this.node = (this.context.createScriptProcessor ||
                 this.context.createJavaScriptNode).call(this.context,
                 bufferLen, numChannels, numChannels);


    stream.connect(this.node);
    this.node.connect(this.context.destination);    

    this.node.onaudioprocess = function(e){
      if (!recording) return;
      for (var i = 0; i < numChannels; i++){
          if(!recordBuffers[i])  recordBuffers[i] = [];
          recordBuffers[i].push.apply(recordBuffers[i], e.inputBuffer.getChannelData(i));
      }
    }

    this.getData = function(){
        var tmp = recordBuffers;
        recordBuffers = [];
        return tmp;     // returns an array of array containing data from various channels
    };

    this.start() = function(){
        recording = true;
    };

    this.stop() = function(){
        recording = false;
    };

}

example usage:

var recorder = new RecordAudio(userMedia);
recorder.start();
recorder.stop();
var recordedData = recorder.getData();