OSC message demo

Send Open Sound Control 1.0 messages between windows to control a synth.

by rectang

HTML

<p>
  This Fiddle demonstrates sending Open Sound Control 1.0 messages from a "controller" window to a bare-bones implementation of audio synthesis built using the Web Audio API.
</p>

<p>
  Launching the demo will open a small red window. Click that window to make a tone sound.
</p>

<input type='button' id="launcher" value="launch controller" />

JavaScript

function launchDemo() {
  var audioContext =
    new (window.AudioContext || window.webkitAudioContext);
  var oscillator = audioContext.createOscillator();
  var gain = audioContext.createGain();
  oscillator.frequency.value = 440;
  gain.gain.value = 0.3;
  oscillator.start();
  oscillator.connect(gain);

  var winFeatures = "menubar=no,location=no,resizable=no," +
    "scrollbars=no,status=no,titlebar=no,toolbar=no," +
    "height=50,width=50";
  var controllerWin =
    window.open('', "_blank", winFeatures);
  controllerWin.document.body.style =
    'background-color: red; margin: 0px;';

  var sendSoundOn = function() {
    var message = Uint8Array.from(
      "/mysynth/sound/on\0\0\0,\0\0\0"
      .split('')
      .map(function(c) {
        return c.charCodeAt(0);
      })
    );
    controllerWin.opener.postMessage(message, '*');
  }

  var sendSoundOff = function() {
    var message = Uint8Array.from(
      "/mysynth/sound/off\0\0,\0\0\0"
      .split('')
      .map(function(c) {
        return c.charCodeAt(0);
      })
    );
    controllerWin.opener.postMessage(message, '*');
  }

  controllerWin.document.onmousedown = sendSoundOn;
  controllerWin.document.onmouseup = sendSoundOff;

  var oscListen = function(e) {
    var address =
      String.fromCharCode.apply(null, e.data)
      .split('\0')[0];
    if (address === '/mysynth/sound/on') {
      gain.connect(audioContext.destination);
    } else if (address === '/mysynth/sound/off') {
      gain.disconnect(audioContext.destination);
    }
  }

  window.addEventListener('message', oscListen);
}

document.getElementById('launcher').onclick = launchDemo;

/* Content of this Fiddle by Marvin Humphrey
 *
 * To the extent possible under law, the person who
 * associated CC0 with the Content of this Fiddle
 * has waived all copyright and related or neighboring
 * rights to the Content of this Fiddle.
 *
 * See <http://creativecommons.org/publicdomain/zero/1.0/>.
 */