HTML5 setting audio source in javascript not working

后端 未结 3 1094
终归单人心
终归单人心 2020-12-17 19:02

Due to HTML5 browser formats tricks I have to put fallback audio formats also in audio format. I want to set the src of source in audio programmatically but it is not worki

相关标签:
3条回答
  • 2020-12-17 19:05

    After you set the src attribute on the source element, call load() and then play() on the audio element. (Or, just load() if you have the autoplay attribute set.)

    0 讨论(0)
  • 2020-12-17 19:10

    Have you tried document.getElementById("oggSource").src = 'OggFormat.ogg' etc.?

    0 讨论(0)
  • 2020-12-17 19:17

    Using .detach().appendTo(parent) seems to work: http://jsfiddle.net/pimvdb/b7Jgh/.

    $("#oggSource").attr("src", "foo.ogg").detach().appendTo("#audioPlayer");
    

    I guess the browser only starts loading (and playing with autoplay) if a <source> element is added, not when it is just modified. I'm not sure why though, but appending it after detaching works.


    Edit: You can also directly do .appendTo since an element is unique (i.e. it has to be detached anyway): http://jsfiddle.net/pimvdb/b7Jgh/6/.

    function updateSource(source, src) {
        source = $(source);
        source.attr("src", src).appendTo(source.parent());
    }
    
    0 讨论(0)
提交回复
热议问题