Real time audio processing with Web Audio API

HTML

<h1>Real time audio processing with Web Audio API</h1>

<p>You should hear your own voice played back with a delay mixed with noise.</p>

<p>You may need to press the "allow" button above</p>

<a href="http://papers.traustikristjansson.info/?p=486">See the tutorial here.</a>

CSS

h1 {
    font-family: Helvetica, Arial;   
    font-weight: bold;
    font-size: 18px;
}

body, p{
    font-family: Helvetica, Arial;
}

JavaScript

function myPCMFilterFunction(inputSample) {
  var noiseSample = Math.random() * 2 - 1;
  return inputSample + noiseSample * 0.1;  // For example, add noise samples.
}

// The rest is boilerplate.

// Check if Web Audio API is supported.
var audioContext;
try {
  window.AudioContext = window.AudioContext || window.webkitAudioContext;
  audioContext = new AudioContext();
} catch(e) {
  alert('Web Audio API is not supported in this browser');
}

// Check if there is microphone input.
try {
  navigator.getUserMedia = navigator.getUserMedia ||
                           navigator.webkitGetUserMedia ||
                           navigator.mozGetUserMedia ||
                           navigator.msGetUserMedia;
  var hasMicrophoneInput = (navigator.getUserMedia || navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia || navigator.msGetUserMedia);
} catch(e) {
  alert("getUserMedia() is not supported in your browser");
}

// Create a pcm processing "node" for the filter graph.
var bufferSize = 4096;
var myPCMProcessingNode = audioContext.createScriptProcessor(bufferSize, 1, 1);
myPCMProcessingNode.onaudioprocess = function(e) {
  var input = e.inputBuffer.getChannelData(0);
  var output = e.outputBuffer.getChannelData(0);
  for (var i = 0; i < bufferSize; i++) {
     // Modify the input and send it to the output.
     output[i] = myPCMFilterFunction(input[i]);
  }
}


var errorCallback = function(e) {
  alert("Error in getUserMedia: " + e);
};  

// Get access to the microphone and start pumping data through the  graph.
navigator.getUserMedia({audio: true}, function(stream) {
  // microphone -> myPCMProcessingNode -> destination.
  var microphone = audioContext.createMediaStreamSource(stream);
  microphone.connect(myPCMProcessingNode);
  myPCMProcessingNode.connect(audioContext.destination);
  microphone.start(1);
}, errorCallback);