Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - createOscillator noteOn not working

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...