我正在尝试制作一个HTML5音频播放列表,该列表可在每种主要浏览器上使用:Chrome,Safari,Firefox,IE9 +。但是,我不知道如何以跨浏览器兼容的方式更改源。

更新了例如,更改<source>标记的src在Chrome中有效,但不适用于Safari。虽然下面使用canPlayType的@ eivers88解决方案有效,但对我来说,仅更改<source>标记的src似乎更容易。谁能向我解释为什么我下面的代码可以在Chrome浏览器中运行而不能在Safari中运行?

JS:

var audioPlayer=document.getElementById('audioPlayer');
var mp4Source=$('source#mp4');
var oggSource=$('source#ogg');
$('button').click(function(){
  audioPlayer.pause();
  mp4Source.attr('src', 'newFile.mp4');
  oggSource.attr('src', 'newFile.ogg');
  audioPlayer.load();
  audioPlayer.play();
});

HTML:
<button type="button">Next song</button>
<audio id="audioPlayer">
  <source id="mp4" src="firstFile.mp4" type="audio/mp4"/>
  <source id="ogg" src="firstFile.ogg" type="audio/ogg" />
</audio>

单击按钮后检查HTML,<source src=""/>确实在Safari中发生了变化,只是没有发出HTTP请求,因此它们的文件没有load()play()。有人对此有任何想法吗?

最佳答案

这是一个有效的exapmle。它与您所拥有的有点不同,但是希望这会有所帮助。

HTML:

<button type="button">Next song</button>

Javascript / jquery:
    var songs = [
    '1976', 'Ballad of Gloria Featherbottom', 'Black Powder'
]
var track = 0;
var audioType = '.mp3'
var audioPlayer = document.createElement('audio');

$(window).load(function() {

    if(!!audioPlayer.canPlayType('audio/ogg') === true){
        audioType = '.ogg' //For firefox and others who do not support .mp3
    }

    audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
    audioPlayer.setAttribute('controls', 'controls');
    audioPlayer.setAttribute('id', 'audioPlayer');
    $('body').append(audioPlayer);
    audioPlayer.load();
    audioPlayer.play();

});

$('button').on('click', function(){
    audioPlayer.pause();
    if(track < songs.length - 1){
        track++;
        audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
        audioPlayer.load();
        audioPlayer.play();
    }
    else {
        track = 0;
        audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
        audioPlayer.load();
        audioPlayer.play();
    }
})

09-30 16:38
查看更多