This is a simple query but somehow i can't seem to put a finger to what seems to be going wrong.
I have two buttons namely 'problem' and 'need'. On clicking the former, the audio file 1 needs to be played, similarly when later is clicked the audio file 1 should stop and audio file 2 is played. The code which i have written for the same is this:
var playing = false;
$("#problem").click(function(event) {
$("#audio").html('');
$("#audio").html('<source src="audio/expertise/file1.mp3" type="audio/mp3"><source src="audio/expertise/file1.wav" type="audio/x-wav"><source src="audio/expertise/file1.ogg" type="audio/ogg">');
playing = true;
});
$('.need_btn').attr('id', 'need_btn');
$("#need_btn").click(function(event) {
if (playing == true) {
$("#audio").trigger('pause');
playing = false;
if (playing == false){
$("#audio").attr('src','<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');
$("#audio").trigger('play');
playing = true;
};
}
else{
/*$("#audio").trigger('play');*/
};
});
this works fine for playing file 1 , pause file 1 when second button is clicked but does not play file 2. What can i change to make it work?
I think the problem in your case is this piece of code:
$("#audio").attr('src','<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');
I just went through the official documentation and it seems like you are using the .attr
in an incorrect way. I haven't tried the code I'm going to post, but assuming you do want to set the attributes of the source
element, you might want to try something on these lines:
$( "source" ).attr({
src: "audio/expertise/file2.mp3",
type: "audio/mp3"
});
Now I understand you have the .ogg
, .wav
and the .mp3
versions. So I think it's also possible you directly set the html
for the element with id "audio" like you did with file1
. I'm suggesting something like this:
$("#audio").html('<source src="audio/expertise/file2.mp3" type="audio/mp3"><source src="audio/expertise/file2.wav" type="audio/x-wav"><source src="audio/expertise/file2.ogg" type="audio/ogg">');
This would set the html
for the corresponding element with the required markup. I hope this gets you started in the right direction.