Javascript 如何以编程方式向 HTML5 音频标签添加多个源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4053262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add multiple sources to an HTML5 audio tag, programmatically?
提问by Abhishek Mishra
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>
While with JavaScript, I'm also allowed to create an audio element like this -
使用 JavaScript 时,我也可以创建这样的音频元素 -
var new_audio = document.createElement("audio");
Where I can set its source by the .src
property - new_audio.src="....";
我可以在哪里通过.src
属性设置其来源-new_audio.src="....";
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.
我没有找到如何通过 JavaScript 在音频元素中添加多个源,类似于 HTML 片段中显示的源标记。
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
并在其中添加<source...
标签,就像操作任何其他 DOM 元素一样?我现在正在这样做并且它有效,这是-
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?
我想知道是否有更合适的方法来做到这一点?
回答by robertc
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
.
当您只能检测支持的类型时,为什么要使用 JavaScript 添加多个文件?我建议改为检测最佳类型,然后只设置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.
添加与文件类型一样多的检查。
回答by bobince
You can use the same DOM methods as with any other element:
您可以使用与任何其他元素相同的 DOM 方法:
var source= document.createElement('source');
source.type= 'audio/ogg';
source.src= 'audio/song.ogg';
audio.appendChild(source);
source= document.createElement('source');
source.type= 'audio/mpeg';
source.src= 'audio/song.mp3';
audio.appendChild(source);