Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 203
TCM Avatar asked Oct 28 '11 11:10

TCM


People also ask

How do I change the audio source in JavaScript?

You can change the audio file of the HTML5 player with just one line of JavaScript code that you can see below: document. getElementById("my-audio"). setAttribute('src', 'AUDIO_SRC_FILE');

How do I embed audio in HTML5?

To embed audio in HTML, we use the <audio> tag. Before HTML5, audio cannot be added to web pages in the Internet Explorer era. To play audio, we used web plugins like Flash. After the release of HTML5, it is possible.


2 Answers

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());
}
like image 75
pimvdb Avatar answered Oct 14 '22 15:10

pimvdb


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

like image 27
Shadow2531 Avatar answered Oct 14 '22 15:10

Shadow2531