使用 jquery 和 HTML5 音频标签切换音频源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9421505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:47:27  来源:igfitidea点击:

switch audio source with jquery and HTML5 audio tag

jqueryhtmlaudiohtml5-audio

提问by Daniel Hunter

I have only found one other solution but it was incomplete so I need help here.

我只找到了另一种解决方案,但它不完整,所以我在这里需要帮助。

i have the audio set up:

我有音频设置:

<audio id="player" controls="controls">
          <source id="ogg_src" src="lib/audio/barger01.ogg" type="audio/ogg" />
          <source id="mp3_src" src="lib/audio/barger01.mp3" type="audio/mp3" />
          Your browser does not support the audio element.
    </audio>

I have a dynamically generated table of links to change the track:

我有一个动态生成的链接表来更改轨道:

<div id="audio_list">
   <a href="#" class="track" data-location="http://www.newoggtrack.ogg">sample</a>
</div>

i have this jquery that i have no clue what to do with to change the track

我有这个 jquery,我不知道如何改变轨道

$('.track').click(function(){

    load_track = $(this).attr('data-location');//gets me the url of the new track

    change_track(load_track);// function to change the track of the loaded audio player without page refresh preferred...

});

i found this function but i am not using it the right way

我找到了这个功能,但我没有以正确的方式使用它

 function change_track(sourceUrl) {

        audio.empty();
        $("#ogg_src").attr("src", sourceUrl).appendTo(audio);
        /****************/
        audio[0].pause();
        audio[0].load();//suspends and restores all audio element
        /****************/
    }

audio = $("<audio>").attr("id", "player")
                        .attr("preload", "auto");

回答by Justice Erolin

Your change function should be like this:

您的更改功能应该是这样的:

function change(sourceUrl) {
    var audio = $("#player");      
    $("#ogg_src").attr("src", sourceUrl);
    /****************/
    audio[0].pause();
    audio[0].load();//suspends and restores all audio element

    //audio[0].play(); changed based on Sprachprofi's comment below
    audio[0].oncanplaythrough = audio[0].play();
    /****************/
}

The problems were audio.empty() and the audio var. You were attempting to append an emptied audio tag, and didn't write out the audio tag back to the browser.

问题是 audio.empty() 和音频变量。您试图附加一个清空的音频标签,但没有将音频标签写回浏览器。

回答by Jay Blanchard

You might also want to rename the function since 'change' is already a function in the jQuery universe.

您可能还想重命名该函数,因为 'change' 已经是 jQuery 世界中的一个函数。