为什么这个声音在webaudio api中不断重演?

时间:2015-01-23 19:56:37

标签: javascript audio web-audio

我想用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;
});

1 个答案:

答案 0 :(得分:0)

上面的代码实际上运行正常,我的问题是即时通讯使用中间人和链轮,我正在调用两次脚本。

使用链轮和在layout.erb上手动操作一次