使用 HTML5 更改<源> 音频在 Chrome 中有效,但不适用于 Safari

Changing <source> with HTML5 Audio works in Chrome but not Safari

本文关键字:有效 不适用 Safari 适用于 Chrome 音频 更改 HTML5 使用      更新时间:2023-09-26

我正在尝试制作一个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()编辑。有人对此有任何想法吗?

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

.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();
    }
})

出于某种原因,Safari 浏览器无法使用 <source> 标签在歌曲之间切换,但 Chrome 可以。只需更改加载到<audio>标签上的src属性中的内容即可在Chrome和Safari上工作,但是存在ogg与.mp3问题。

我想解决这个问题.mp3的一种方法是使用Modernizr功能检测来加载Firefox中的ogg mime类型和Chrome/Safari中的mp3。以下是这方面的参考资料:使用 Modernizr 检测 html5 音频支持。

只是对该主题的快速补充(2023 年):

我也有类似的问题。该代码在Safari中有效,但不能在Chrome中工作。我有 Javascript 代码交换了 <source> 元素的src。这在Safari中工作正常,但Chrome拒绝识别该文件并显示禁用播放器状态。我错过的,以及我在这里学到的,是你也需要打电话给load()

所以添加这个为我修复了它。

audioPlayer.load();

Safari似乎会自动检测源更改,Chrome没有。