3

I got this snippet from a website (can't remember where at the moment) and it has stopped working.

I use it to play a tone.

Is it something that I'm doing wrong or has Chrome changed recently?

Play = (function () {
 var ctx = new(window.audioContext || window.webkitAudioContext);
 return function (duration, freq, finishedCallback) {
  duration = +duration;
  if (typeof finishedCallback != "function") {
   finishedCallback = function () {};
  }
  var osc = ctx.createOscillator();
  osc.type = 0;
  osc.connect(ctx.destination);
  osc.frequency.value = freq;
  osc.noteOn(0);
  setTimeout(
   function () {
    osc.noteOff(0);
    finishedCallback();
   }
   ,duration
  );
 };
})();
Play(50,500)
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373

1 Answers1

7

There are two problems here - there is no audioContext (small "a", doesn't affect Chrome at the moment though). Just change it to:

var ctx = new (window.AudioContext || window.webkitAudioContext);

Add support for start(), which is the more recent method. There are several ways to do this, here's a basic example:

if (osc.start) {
    osc.start(0);
}
else {
    osc.noteOn(0);
}

(and of course, osc.noteOff(0)osc.stop(0) as well)

Play = (function() {
  
  var ctx = new(AudioContext || webkitAudioContext);
  
  return function(duration, freq, finishedCallback) {
    duration = +duration;
    if (typeof finishedCallback != "function") {
      finishedCallback = function() {};
    }
    var osc = ctx.createOscillator();
    osc.type = 0;
    osc.connect(ctx.destination);
    osc.frequency.value = freq;
    
    if (osc.start) osc.start();
    else osc.noteOn(0);
    
    setTimeout(
      function() {
        if (osc.stop) osc.stop(0);
        else osc.noteOff(0);
        finishedCallback();
      }, duration
    );
  };
})();
Play(50, 500)