如何以编程方式将多个源添加到HTML5音频标签? [英] How can I add multiple sources to an HTML5 audio tag, programmatically?

查看:144
本文介绍了如何以编程方式将多个源添加到HTML5音频标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多示例演示了嵌套在音频标记中的多个源标记,作为克服不同浏览器之间编解码器兼容性的方法。这样的事情 -

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 -

<audio controls="controls">
  <source src="song.ogg" type="audio/ogg" />
  <source src="song.mp3" type="audio/mpeg" />
  Your browser does not support the audio element.
</audio>

使用JavaScript时,我也可以创建像这样的音频元素 -

While with JavaScript, I'm also allowed to create an audio element like this -

var new_audio = document.createElement("audio");

我可以通过 .src property - new_audio.src =....;

Where I can set its source by the .src property - new_audio.src="....";

我找不到如何添加通过JavaScript在音频元素中添加多个源,类似于HTML代码段中显示的源代码。

I failed to find how to add multiple sources in an audio element through JavaScript, something similar to source tags shown in the HTML snippet.

我是否操纵 new_audio 并在其中添加< source ... 标签,就像操纵任何其他DOM元素一样?我现在正在这样做,它可以工作,这是 -

Do I manipulate the new_audio and add the <source... tags inside it, just like one would manipulate any other DOM element? I'm doing this right now and it works, which is -

new_audio.innerHTML = "<source src='audio/song.ogg' type='audio/ogg' />";
new_audio.play();

我想知道是否有更合适的方法吗?

I wonder if there is a more appropriate way to do it?

推荐答案

为什么只要检测支持的类型,为什么要用JavaScript添加多个文件?我建议改为检测最佳类型,然后设置 src

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.

这篇关于如何以编程方式将多个源添加到HTML5音频标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆