Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

jquery - HTML5 setting audio source in javascript not working

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.

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>

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.

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?

If I use:

<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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using .detach().appendTo(parent) seems to work: http://jsfiddle.net/pimvdb/b7Jgh/.

$("#oggSource").attr("src", "foo.ogg").detach().appendTo("#audioPlayer");

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.


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...