title: slow down/delay frequency display
body: <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>window.AudioContext = window.AudioContext || window.webkitAudioContext;
  
  var audioContext = null;
  var isPlaying = false;
  var sourceNode = null;
  var analyser = null;
  var theBuffer = null;
  var DEBUGCANVAS = null;
  var mediaStreamSource = null;
  var detectorElem, 
   pitchElem ;
  var testdelay = null;
  
  window.onload = function() {
   audioContext = new AudioContext();
   
   //test delay
   //testdelay = audioContext.createDelay(5.0);
   //testdelay.delayTime.value = 3.0;
   
   MAX_SIZE = Math.max(4,Math.floor(audioContext.sampleRate/5000)); // corresponds to a 5kHz signal
   var request = new XMLHttpRequest();
   request.open("GET", "../sounds/whistling3.ogg", true);
   request.responseType = "arraybuffer";
   request.onload = function() {
     audioContext.decodeAudioData( request.response, function(buffer) { 
        theBuffer = buffer;
    } );
   }
   request.send();
  
   detectorElem = document.getElementById( "detector" );
   pitchElem = document.getElementById( "pitch" );
  
  
   detectorElem.ondragenter = function () { 
    this.classList.add("droptarget"); 
    return false; };
   detectorElem.ondragleave = function () { this.classList.remove("droptarget"); return false; };
   detectorElem.ondrop = function (e) {
      this.classList.remove("droptarget");
      e.preventDefault();
    theBuffer = null;
  
      var reader = new FileReader();
      reader.onload = function (event) {
       audioContext.decodeAudioData( event.target.result, function(buffer) {
         theBuffer = buffer;
       }, function(){alert("error loading!");} ); 
  
      };
      reader.onerror = function (event) {
       alert("Error: " + reader.error );
    };
      reader.readAsArrayBuffer(e.dataTransfer.files[0]);
      return false;
   };
  }
  
  function error() {
      alert('Stream generation failed.');
  }
  
  function getUserMedia(dictionary, callback) {
      try {
          navigator.getUserMedia = 
           navigator.getUserMedia ||
           navigator.webkitGetUserMedia ||
           navigator.mozGetUserMedia;
          navigator.getUserMedia(dictionary, callback, error);
      } catch (e) {
          alert('getUserMedia threw exception :' + e);
      }
  }
  
  function gotStream(stream) {
      // Create an AudioNode from the stream.
      mediaStreamSource = audioContext.createMediaStreamSource(stream);
   
      // Connect it to the destination.
      analyser = audioContext.createAnalyser();
  
   //test delay
   //testdelay = audioContext.createDelay(5.0);
   //testdelay.delayTime.value = 3.0;
   
   
   //analyser.smoothingTimeConstant = 0.8;
   
      analyser.fftSize = 8192;
      mediaStreamSource.connect( analyser );
   
      updatePitch();
  }
  
  function toggleLiveInput() {
      if (isPlaying) {
          //stop playing and return
          sourceNode.stop( 0 );
          sourceNode = null;
          analyser = null;
          isPlaying = false;
    if (!window.cancelAnimationFrame)
     window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
          window.cancelAnimationFrame( rafID );
      }
      getUserMedia(
       {
              "audio": {
                  "mandatory": {
                      "googEchoCancellation": "false",
                      "googAutoGainControl": "false",
                      "googNoiseSuppression": "false",
                      "googHighpassFilter": "false"
                  },
                  "optional": []
              },
          }, gotStream);
  }
  
  
  var buf = new Float32Array( 1024 );
  
  
  var MIN_SAMPLES = 0;  // will be initialized when AudioContext is created.
  
  function autoCorrelate( buf, sampleRate ) {
   var SIZE = buf.length;
   var MAX_SAMPLES = Math.floor(SIZE/2);
   var best_offset = -1;
   var best_correlation = 0;
   var rms = 0;
   var foundGoodCorrelation = false;
   var correlations = new Array(MAX_SAMPLES);
  
   for (var i=0;i&lt;SIZE;i++) {
    var val = buf[i];
    rms += val*val;
   }
   
   rms = Math.sqrt(rms/SIZE);
   if (rms&lt;0.01) // not enough signal
    return -1;
  
   
   var lastCorrelation=1;
   for (var offset = MIN_SAMPLES; offset &lt; MAX_SAMPLES; offset++) {
    var correlation = 0;
  
    for (var i=0; i&lt;MAX_SAMPLES; i++) {
     correlation += Math.abs((buf[i])-(buf[i+offset]));
    }
    
    correlation = 1 - (correlation/MAX_SAMPLES);
    
    // store it, for the tweaking we need to do below.
    correlations[offset] = correlation; 
    
    if ((correlation&gt;0.9) &amp;&amp; (correlation &gt; lastCorrelation)) {
     foundGoodCorrelation = true;
     if (correlation &gt; best_correlation) {
      best_correlation = correlation;
      best_offset = offset;
     }
    } else if (foundGoodCorrelation) {
     var shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset];  
     return sampleRate/(best_offset+(8*shift));
    }
    
    lastCorrelation = correlation;
   }
   if (best_correlation &gt; 0.01) {
    // console.log("f = " + sampleRate/best_offset + "Hz (rms: " + rms + " confidence: " + best_correlation + ")")
    return sampleRate/best_offset;
   }
   return -1;
  // var best_frequency = sampleRate/best_offset;
  }
  
  
  //Fungsi untuk melakukan Update/perubahan data frequensi
  function updatePitch( time ) {
   var cycles = new Array;
   analyser.getFloatTimeDomainData( buf );
   analyser.smoothingTimeConstant = 0.8;
   var ac = autoCorrelate( buf, audioContext.sampleRate );
   
   //menampilkan data pada form
   //jika tidak ditemukanya gelombang maka data akan kosong, dan warna tampilan akan abu2
    if (ac == -1) {
     detectorElem.className = "vague";
     pitchElem.innerText = "";
  
   //jika ditemukanya gelombang maka data akan kosong, dan warna tampilan akan hitam dan data akan ditampilkan
    } else {
     detectorElem.className = "confident";
     pitch = ac;
    
    //menampilkan data "pitch" (--Hz) pada halaman Web
     pitchElem.innerText = Math.round( pitch ) ;
   }
  
   if (!window.requestAnimationFrame)
    window.requestAnimationFrame = window.webkitRequestAnimationFrame;
   rafID = window.requestAnimationFrame( updatePitch );
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Pitch Detector&lt;/title&gt;
  &lt;link href='http://fonts.googleapis.com/css?family=Alike' rel='stylesheet' type='text/css'&gt;
  &lt;style&gt;
  body { font: 14pt 'Alike', sans-serif;}
  #note { font-size: 164px; }
  .droptarget { background-color: #348781}
  div.confident { color: black; }
  div.vague { color: lightgrey; }
  #note { display: inline-block; height:180px; text-align: left;}
  
  #detector { width: 300px; height: 300px; border: 4px solid gray; border-radius: 8px; text-align: center; padding-top: 10px;}
  #output { width: 300px; height: 42px; }
  #flat { display: none; }
  #sharp { display: none; }
  .flat #flat { display: inline; }
  .sharp #sharp { display: inline; }
  &lt;/style&gt;
  
  &lt;/head&gt;
  &lt;body&gt;
  &lt;script src="js/pitchdetect.js"&gt;&lt;/script&gt;
   
  &lt;!--  &lt;button onclick="this.innerText = togglePlayback()"&gt;use demo audio&lt;/button&gt; --&gt;
  &lt;center&gt;
  &lt;button onclick="toggleLiveInput()"&gt;use live input&lt;/button&gt;
  
  &lt;!--&lt;button onclick="updatePitch(0);"&gt;sample&lt;/button&gt;--&gt;
  
  &lt;div id="detector" class="vague"&gt;
   &lt;div class="pitch"&gt;&lt;span id="pitch"&gt;--&lt;/span&gt;Hz&lt;/div&gt;
   &lt;div class="note"&gt;&lt;span id="note"&gt;--&lt;/span&gt;&lt;/div&gt;   
   &lt;canvas id="output" width=300 height=42&gt;&lt;/canvas&gt;
   &lt;div id="detune"&gt;&lt;span id="detune_amt"&gt;--&lt;/span&gt;&lt;span id="flat"&gt;cents &amp;#9837;&lt;/span&gt;&lt;span id="sharp"&gt;cents &amp;#9839;&lt;/span&gt;&lt;/div&gt;
  &lt;/div&gt;
  
  
  &lt;!-- just used for debugging
  &lt;canvas id="waveform" width="512" height="256"&gt;&lt;/canvas&gt;
  --&gt;
  
  &lt;script type="text/javascript"&gt;
  
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-35593052-1']);
    _gaq.push(['_trackPageview']);
  
    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
  
  &lt;/script&gt;
  &lt;/center&gt;
  &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>did anyone have experience making a live frequency meter on web (php,javascript) using microphone?</p>
  
  <p>i have a project to make a online live frequency meter. to display frequency number so we can record if the product were good or not. 
  but the frequency number run too fast..</p>
  
  <p>can  any one help me, how to skip some updatePicht() or some way to delay the display, for making it easier to look?
  or the way to smooth the value...</p>