上面的答案在当时是正确的,但现在是错误的;你可以用纯javascript来做。但是,使用javascript的答案不再有效,其他答案非常有限,或者不使用纯javascript。 我做了我自己的解决方案,效果很好,可以让你控制音量,频率和波型。 //if you have another AudioContext class use that one, as some browsers have a limit
var audioCtx = new (window.AudioContext || window.webkitAudioContext || window.audioContext);
//All arguments are optional:
//duration of the tone in milliseconds. Default is 500
//frequency of the tone in hertz. default is 440
//volume of the tone. Default is 1, off is 0.
//type of tone. Possible values are sine, square, sawtooth, triangle, and custom. Default is sine.
//callback to use on end of tone
function beep(duration, frequency, volume, type, callback) {
var oscillator = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
if (volume){gainNode.gain.value = volume;}
if (frequency){oscillator.frequency.value = frequency;}
if (type){oscillator.type = type;}
if (callback){oscillator.onended = callback;}
oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + ((duration || 500) / 1000));
};有人建议我编辑这段代码,指出它只适用于某些浏览器。然而,据我所知,所有现代浏览器上都有Audiocontext seems to be supported。它在IE上不受支持,但微软已经停止使用。如果您在特定浏览器上遇到任何问题,请报告。
|