我想用webaudio api播放声音,但是音频会不断地自身重新触发,从而增加了疯狂的混乱声。
我遵循了本教程:http://fourthof5.com/audio-visualisation-with-the-web-audio-api
我不太了解整个代码,但是我认为声音并没有被告知要在任何地方重新触发。
但是,它每隔几秒钟就会播放一次。
有任何想法吗 ?
谢谢
码:
/* Hoist some variables. */
var audio, context;
/* Try instantiating a new AudioContext, throw an error if it fails. */
try {
/* Setup an AudioContext. */
context = new AudioContext();
} catch(e) {
throw new Error('The Web Audio API is unavailable');
}
/* Define a `Sound` Class */
var Sound = {
/* Give the sound an element property initially undefined. */
element: undefined,
/* Define a class method of play which instantiates a new Media Element
* Source each time the file plays, once the file has completed disconnect
* and destroy the media element source. */
play: function() {
var sound = context.createMediaElementSource(this.element);
this.element.onended = function() {
sound.disconnect();
sound = null;
}
sound.connect(context.destination);
/* Call `play` on the MediaElement. */
this.element.play();
}
};
/* Create an async function which returns a promise of a playable audio element. */
function loadAudioElement(url) {
return new Promise(function(resolve, reject) {
var audio = new Audio();
audio.addEventListener('canplay', function() {
/* Resolve the promise, passing through the element. */
resolve(audio);
});
/* Reject the promise on an error. */
audio.addEventListener('error', reject);
audio.src = url;
});
}
/* Let's load our file. */
loadAudioElement('/audio/sound.wav').then(function(elem) {
/* Instantiate the Sound class into our hoisted variable. */
audio = Object.create(Sound);
/* Set the element of `audio` to our MediaElement. */
audio.element = elem;
/* Immediately play the file. */
audio.play();
}, function(elem) {
/* Let's throw an the error from the MediaElement if it fails. */
throw elem.error;
});
最佳答案
上面的代码实际上运行良好,我的问题是我使用中间人和链轮,而我两次调用了脚本。
一次用链轮,一次在layout.erb上手动
关于javascript - 为什么此声音会在webaudio api中不断重新触发?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28117722/