Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

html - switch audio source with jquery and HTML5 audio tag

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

$('.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");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...