CreateOscillator noteOn not working

I got this snippet from the website (I can’t remember where at the moment), and it stops working.

I use it to reproduce the tone.

Is this something I'm doing wrong or have recently changed Chrome?

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) 
+1
source share
1 answer

There are two problems here: there is no audioContext (a little "a" does not currently affect Chrome). Just change it to:

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

Add support for start (), which is a later method. There are several ways to do this, here is a basic example:

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

(and, of course, osc.noteOff(0) ➜ osc.stop(0) )

 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) 
+4
source

Source: https://habr.com/ru/post/984513/


All Articles