How can I add multiple sources to an HTML5 audio tag, programmatically?

前端 未结 2 1072
清歌不尽
清歌不尽 2020-11-29 05:43

A lot of examples demonstrate multiple source tags nested in the audio tag, as a method to overcome codec compatibility across different browsers. Something like this -

2条回答
  •  时光取名叫无心
    2020-11-29 06:36

    Why add multiple files with JavaScript when you can just detect the types supported? I would suggest instead detecting the best type then just setting the src.

    var source= document.createElement('source');
    if (audio.canPlayType('audio/mpeg;')) {
        source.type= 'audio/mpeg';
        source.src= 'audio/song.mp3';
    } else {
        source.type= 'audio/ogg';
        source.src= 'audio/song.ogg';
    }
    audio.appendChild(source);
    

    Add as many checks as you have file types.

提交回复
热议问题