Lightsensor Theremin

by codepo8

HTML

<h1>Lightsensor Theremin</h1> 

<p>Move your hand closer and further away from the camera on your Macbook (or phone, or PC) to create lower and higher sounds. This needs a browsers with devicelight and web audio capabilities (yes, Firefox).</p>
<output>400</output>
<button>stop/start sound</button>

CSS

body {
    font-family: helvetica, arial, sans-serif;
}
output {
    display: block; 
    font-size: 80px;
    color: #666;
}

JavaScript

var out = document.querySelector('output');
var button = document.querySelector('button');
var playing = true;
var freq = 400;
window.addEventListener('devicelight', function(e) {
  freq = e.value * 10;
  oscillator.frequency.value = freq;
  out.innerHTML = freq; 
},false);
button.addEventListener('click', function(e){
    if (playing) { 
        oscillator.stop(0); playing = false;
    } else {
        startSound(); playing = true;
    }    
},false);
function startSound() {
    context = new AudioContext;
    oscillator = context.createOscillator();
    oscillator.connect(context.destination);
    oscillator.start(0);
}
startSound();