使用HTML5音频更改<source>适用于Chrome,但不适用于Safari

tim*_*son 3 javascript safari jquery html5 html5-audio

我正在尝试制作可在每个主要浏览器中使用的HTML5音频播放列表:Chrome,Safari,Firefox,IE9 +.但是,我无法弄清楚如何以跨浏览器兼容的方式更改源.

更新例如,更改<source>标签src可在Chrome中使用,但不适用于Safari.虽然@ eivers88的解决方案在下面使用,canPlayType但我更容易改变<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();
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

eiv*_*s88 5

这是一个工作的exapmle.它与你所拥有的有点不同,但希望这会有所帮助.

HTML:

<button type="button">Next song</button>
Run Code Online (Sandbox Code Playgroud)

使用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();
    }
})
Run Code Online (Sandbox Code Playgroud)