Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  52] [ 5]  / answers: 1 / hits: 15453  / 13 Years ago, fri, october 28, 2011, 12:00:00

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.


More From » jquery

 Answers
37

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

[#89402] Thursday, October 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jensenb

Total Points: 634
Total Questions: 102
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;