我使用 AudioContext 在我的网站中播放一些音频。它适用于 Chrome 和 Firefox,但不适用于 Safari。在 Safari 上stop
功能不起作用,我得到以下信息:
[错误] InvalidStateError:DOM 异常 11:尝试使用不可用或不再可用的对象。noteOff(preload.js,第 85 行)
有谁知道,如何解决这个问题,以及为什么会出现这个错误?
function _initWebAudio(AudioContext, format, audios, callback) {
var context = new AudioContext();
preloader(audios, _preload, callback);
function _preload(asset, doneCallback) {
var request = new XMLHttpRequest();
request.open('GET', 'audio/' + asset.id + '.' + format, true);
request.responseType = 'arraybuffer';
request.onload = function () {
context.decodeAudioData(request.response, function (buffer) {
var source;
// default volume
//// support both webkitAudioContext or standard AudioContext
asset.gain = context.createGain ? context.createGain() : context.createGainNode();
asset.play = function () {
source = context.createBufferSource(); // creates a sound source
source.buffer = buffer; // tell the source which sound to play
source.connect(asset.gain); // connect the source to the context's destination (the speakers)
asset.gain.connect(context.destination);
// play the source now
// support both webkitAudioContext or standard AudioContext
source.noteOn ? source.noteOn(0) : source.start(0);
};
asset.stop = function () {
console.log(source);
source = context.createBufferSource(); // creates a sound source
source.noteOff ? source.noteOff(0) : source.stop(0);
}
asset.toggleVolume = function (muteSound) {
if (muteSound) {
asset.gain.gain.value = 0;
} else {
asset.gain.gain.value = 1;
}
}
doneCallback();
}, function (err) {
asset.play = function () {
};
doneCallback(err, asset.id);
});
};
request.onerror = function (err) {
console.log(err);
asset.play = function () {
};
doneCallback(err, asset.id);
};
// kick off load
request.send();
}
}