HTML5设置javascript中的音频源不起作用
由于HTML5浏览器格式的技巧,我必须将音频格式也采用备用音频格式。我想以编程方式设置音频源的src,但它不起作用。
Due to HTML5 browser formats tricks I have to put fallback audio formats also in audio format. I want to set the src of source in audio programmatically but it is not working.
这是我的HTML代码:
This is my HTML code:
<audio id="audioPlayer" width="400" height="30" controls="controls">
<source id="oggSource" type="audio/ogg" />
<source id="mp3Source" type="audio/mp3" />
</audio>
然后在javascript中使用jquery我为每个人设置了源码(我有一个音频标签和许多在页面上的MP3和基于一些事件我想改变音频标签的来源),所以我不能直接在音频中指定src,主要是因为我需要后备支持,并且我还需要活力。
Then in javascript using jquery I set the source for each of them (I have one audio tag and many mp3 on page and based on some event I want to change the source of audio tag) so I can't specify src directly in audio mainly because I need fallback support and also I need dynamism.
使用jquery我操纵src:
Using jquery I manipulate the src:
$('#oggSource').attr('src', 'OggFormat.ogg');
$('#mp3Source').attr('src','Mp3Format.mp3');
但这是行不通的。知道为什么吗?
But this however doesn't work. Any idea why?
如果我使用:
<audio id="audioPlayer" width="400" height="30" controls="controls">
<source id="oggSource" type="audio/ogg" src="OggFormat.ogg" />
<source id="mp3Source" type="audio/mp3" src="Mp3Format.mp3"/>
</audio>
它有效但我需要在代码中设置它而不是静态提供。
it works but as I need I need to set it in code and not provide statically.
使用 .detach()。appendTo(parent)
似乎有效: http://jsfiddle.net/pimvdb/b7Jgh/ 。
Using .detach().appendTo(parent)
seems to work: http://jsfiddle.net/pimvdb/b7Jgh/.
$("#oggSource").attr("src", "foo.ogg").detach().appendTo("#audioPlayer");
我猜浏览器只会开始加载(并且在玩 autoplay $如果
< source>
元素被添加,而不是刚刚修改时,我不确定为什么,但在分离后附加它。
I guess the browser only starts loading (and playing with autoplay
) if a <source>
element is added, not when it is just modified. I'm not sure why though, but appending it after detaching works.
编辑:你也可以直接使用 .appendTo
,因为一个元素是唯一的(即它必须被分离): http://jsfiddle.net/pimvdb/b7Jgh/6/ 。
You can also directly do .appendTo
since an element is unique (i.e. it has to be detached anyway): http://jsfiddle.net/pimvdb/b7Jgh/6/.
function updateSource(source, src) {
source = $(source);
source.attr("src", src).appendTo(source.parent());
}