I have an audio element with a default source. I want to be able to dynamically change the audio source using jQuery. My code below changes the source but always plays the default audio. Any help would be much appreciated. Thanks.
<audio id="audio_player">
<source id="audio_player_ogv" src="test.ogv" type="audio/ogg" />
<source id="audio_player_mp3" src="test.mp3" type="audio/mpeg" />
</audio>
<a class="change_audio" rel="new_test" href="javascript:;">Change Audio</a>
$('.change_audio').click(function() {
var new_audio = $(this).attr('rel');
$('#audio_player_ogv').attr('src',new_audio+'.ogv').detach().appendTo($('#audio_player'));
$('#audio_player_mp3').attr('src',new_audio+'.mp3').detach().appendTo($('#audio_player'));
var aud = $('#audio_player').get(0);
aud.play();
});
I would do:
<div id="divAudio_Player">
<audio id="audio_player">
<source id="audio_player_ogv" src="test.ogv" type="audio/ogg" />
<source id="audio_player_mp3" src="test.mp3" type="audio/mpeg" />
</audio>
</div>
<a class="change_audio" rel="new_test" href="javascript:;">Change Audio</a>
$('.change_audio').click(function() {
var new_audio = $(this).attr('rel');
var source = '<audio id="audio_player">';
source += '<source id="audio_player_ogv" src="' + new_audio + '.ogv" type="audio/ogg" />';
source += '<source id="audio_player_ogv" src="' + new_audio + '.mp3" type="audio/mpeg" />';
source += '</audio>';
$('#divAudio_Player').html(source);
var aud = $('#audio_player').get(0);
aud.play();
});
Instead of using <source>
tag, assign source to src
attribute of <audio>
tag. It works. In return, you have to manually check browser type to choose between audio formats to load.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With