Loading Audio Element After Dynamically Changing the Source

前端 未结 3 699
攒了一身酷
攒了一身酷 2021-01-02 20:16

I have a couple of audio elements that appear in the body of my page. They look like this.

      
相关标签:
3条回答
  • 2021-01-02 20:57

    load() followed by play() right away leads to trouble. Trying listening for the canplay event before attempting to play the audio as suggested in https://stackoverflow.com/a/8705478/1374208

    0 讨论(0)
  • 2021-01-02 20:59

    This is tricky. I would try replacing the whole <audio> element instead of just changing its source. This way, the new audio element hasn't been added to the page, so it will be forced to load the file.

    0 讨论(0)
  • 2021-01-02 21:12

    You should call load like this:

    var audio = $("#sound1")[0];
    $("#ChoiceA").mouseenter(function () {
       audio.load();
       audio.play();
    });
    var audio2 = $("#sound2")[0];
    $("#ChoiceB").mouseenter(function () {
       audio.load();
       audio2.play();
    });
    

    Have not tested doing it like above, but have testet this previously with a seperate function looking something like this:

    <audio id="sound1" preload="auto" src="../../Content/Audio/gau.mp3">
    
    function changeAudio(){
        audio = document.getElementById("sound1");
        audio.src = "../../Content/Audio/" + data.nouns[0].Audio1 + ".mp3";
        audio.load();
        audio.play();
    }
    
    $("#ChoiceA").mouseenter(function () {
        changeAudio();
    });
    

    and that worked fine for me?


    EDIT: Adding a fiddle, maybe that will help you figure this out?

    http://jsfiddle.net/Z3VrV/

    0 讨论(0)
提交回复
热议问题