12

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.

3 Answers 3

15

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Great!! I wasted 1 hour behind this thinking I have done something wrong :)
Doesn't work on android browser but does work in chrome for android
2

After you set the src attribute on the source element, call load() and then play() on the audio element. (Or, just load() if you have the autoplay attribute set.)

3 Comments

doesn't work atleast in Chrome. Calling load() didn't do anything and calling play() $('#audioPlayer').play() threw exception that no method named play exists.
@Anthony, you have to call these on the element itself, not the Jquery object. Maybe <stackoverflow.com/questions/47837/…> is what you need? I don't use Jquery, so don't know.
Hmmm.. Right..calling it on jquery doesn't work in this case.
0

Have you tried document.getElementById("oggSource").src = 'OggFormat.ogg' etc.?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.