HTML5 setting audio source in javascript not working

后端 未结 3 1095
终归单人心
终归单人心 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: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 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());
    }
    

提交回复
热议问题