简体   繁体   English

Webaudio,播放声音两次

[英]Webaudio, play sound twice

I am experimenting with WebAudio and I am loading in a sound with the following javascript code. 我正在试验WebAudio,并使用以下javascript代码加载声音。

function playAudio(){
    var audio = document.getElementById('music');
    var audioContext = new webkitAudioContext();
    var analyser = audioContext.createAnalyser();
    var source = audioContext.createMediaElementSource(audio);
    source.connect(analyser);
    analyser.connect(audioContext.destination);
    audio.play();
}

I also want to analyse the sound can visualise it with canvas, hence the analyser . 我还想分析声音,可以使用画布将其可视化,因此可以使用analyser It works fine the first time but if I run this function twice I get an error. 第一次运行正常,但是如果我两次运行此函数,则会出现错误。

> playAudio(); // works fine, i can hear a sound
> playAudio(); // error 
InvalidStateError: Failed to execute 'createMediaElementSource' on 'AudioContext': invalid HTMLMediaElement.

What is causing this error? 是什么导致此错误? I know that the error is caused by this line of code: 我知道错误是由以下代码行引起的:

var source = audioContext.createMediaElementSource(audio);

I am creating a new audio context, so I would assume that I can re-use the same audio element in my html. 我正在创建一个新的音频上下文,因此我假设我可以在html中重复使用相同的音频元素。

By creating the audio element dynamically (as shown in this fiddle, http://jsfiddle.net/ikerr/WcXHK/ ), I was able to play the song repeatedly. 通过动态创建音频元素(如该小提琴中所示, http://jsfiddle.net/ikerr/WcXHK/ ),我能够重复播放歌曲。

function createAudioElement(urls) {
    var audioElement = document.createElement("audio");

    audioElement.autoplay = true;
    audioElement.loop = false;

    for (var i = 0; i < urls.length; ++i) {
        var typeStr = "audio/" + urls[i].split(".").pop();

        if (audioElement.canPlayType === undefined ||
            audioElement.canPlayType(typeStr).replace(/no/, "")) {
            var sourceElement = document.createElement("source");
            sourceElement.type = typeStr;
            sourceElement.src = urls[i];
            audioElement.appendChild(sourceElement);
            console.log("Using audio asset: " + urls[i]);
        }
    }

    return audioElement;
}

var audioContext = new webkitAudioContext();

function playAudio(){

    var audio = createAudioElement(['http://www.soundjay.com/button/button-1.mp3' ]);      

    if(audio){
        var source = audioContext.createMediaElementSource(audio);
        var analyser = audioContext.createAnalyser();
        source.connect(analyser);
        analyser.connect(audioContext.destination);
        audio.play();
    }
}

playAudio(); // works fine, i can hear a sound
playAudio();
//setTimeout(playAudio,2000);

Demo : http://jsfiddle.net/raathigesh/fueg3mk7/10/ 演示: http : //jsfiddle.net/raathigesh/fueg3mk7/10/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM