Inverted-waveform-cancellation.js

From SoundDB
Revision as of 23:42, 7 February 2011 by Admin (talk | contribs) (Created page with "<pre> Inverted Waveform Cancellation Using the Mozilla Audio Data API by F1LT3R @ http://Bocoup.com: // This example is illustrative and not enhanced for performance ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
/*
  Inverted Waveform Cancellation
  Using the Mozilla Audio Data API
  by F1LT3R @ http://Bocoup.com
*/

// This example is illustrative and not enhanced for performance
 
// Define event in global/"window" scope
var audioAvailable;
 
// When the DOM has loaded...
function init(){
  
  // Variable declarations
  var inputSamples, outputSamples, chan1, chan2, i, len,
      output = document.createElement('audio'),   
      debug = document.getElementById('debug'),
      inverted = 1;
         
  // Toggle inversion on Channel 2
  document.getElementById('invertCheckbox').addEventListener('click', function(){ inverted*=-1; },false);
  
  // Initiate the 
  output.mozSetup(2, 44100, 1);
  
  // WHEN SOUND HAPPENS.........>
  audioAvailable = function audioAvailable(event){
  
    // Alias buffer samples to a more conveinient name
    inputSamples = event.frameBuffer;
        
    // Set new length and clear channel data
    var len = inputSamples.length, chan1 = [], chan2 = [], outputSamples = [];
       
    // Copy Audio-Data from <audio> input to Channel 1 into a Native JS Array
    for(i=0;i < len; i++){
      chan1[i]= inputSamples[i];
    }  
 
    // Copy inverted Audio-Data from <audio> input to Channel 2 into a Native JS Array
    for(i=0;i < len; i++){
      chan2[i] = inputSamples[i]*-inverted;
    }
    
    // Mix down Channel 1 and Channel 2
    for(i=0;i < len; i++){
      outputSamples[i] = (chan1[i] + chan2[i]) / 2;
    }
 
    // Display 5 samples from each buffer-written-(event at C level)
    debug.innerHTML = "";
    for(i=0;i<5;i++){
      debug.innerHTML += "<b>"+event.time.toFixed(2) + ":</b>  "+ outputSamples[i]+"<br>";
    }     
    
    // Output mixed samples to <audio> element
    output.mozWriteAudio(outputSamples);
   
  };    
      
  var input = document.getElementById('input');
  input.volume = 0;
  input.addEventListener("MozAudioAvailable", audioAvailable, false);

  //.addEventListener('mozAudioAvailable', function(){ mozAudioAvailable(event) }, false);
};
 
// Call ready event when DOM is loaded
addEventListener('DOMContentLoaded', function(){init();}, false);