Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 jQuery change audio source dynamically

Tags:

html

jquery

audio

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();
});
like image 716
mike Avatar asked Nov 15 '11 08:11

mike


2 Answers

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();
});
like image 128
Chris - Haddox Technologies Avatar answered Oct 26 '22 14:10

Chris - Haddox Technologies


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.

like image 44
Moe Sweet Avatar answered Oct 26 '22 12:10

Moe Sweet