White Noise Example

by Aqilah Misuary

HTML

<title>AudioBuffer example</title>

    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  
  <body>
    <h1>AudioBuffer example</h1>
    <button>Make white noise</button>
    <pre></pre>
  </body>

JavaScript

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var button = document.querySelector('button');
var pre = document.querySelector('pre');
var myScript = document.querySelector('script');

var errorCallback = function(e) {
  alert("Error in getUserMedia: " + e);
};  
// 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");
}

navigator.getUserMedia({audio: true}, function(stream) {
 // microphone -> myPCMProcessingNode -> destination.
  var microphone = audioCtx.createMediaStreamSource(stream);
	var scriptNode = audioCtx.createScriptProcessor();
	
	scriptNode.onaudioprocess = function(audioProcessingEvent) {
  // The input buffer is the song we loaded earlier
  var inputBuffer = audioProcessingEvent.inputBuffer;

  // The output buffer contains the samples that will be modified and played
  var outputBuffer = audioProcessingEvent.outputBuffer;

  // Loop through the output channels (in this case there is only one)
  for (var channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
    var inputData = Array.prototype.reverse.call(inputBuffer.getChannelData(channel));
    var outputData = outputBuffer.getChannelData(channel);
		//console.log(outputData);
		
    // Loop through the 4096 samples
    for (var sample = 0; sample < inputBuffer.length; sample++) {
      // make output equal to the same as the input
     outputData[sample] = inputData[sample];
			
      // add noise to each output sample
      //outputData[sample] += ((Math.random() * 2) - 1) * 0.2;         
    }
 ...