Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic sounds not playing after two plays

I have a little html5 application where you can play a sound by clicking a button.

I have a function that adds an <audio> tag to a <div> with an id "playing." The sound removes itself when it is done.

function sound(track){
$("#playing").append("<audio src=\"" + track + "\" autoplay onended=\"$(this).remove()\"></audio>");
}

For the button I have:

<button onclick="sound('sounds/tada.mp3')">Tada</button>

When I click the button, an <audio> briefly appears in the element inspector and disappears when it is finished, just the way I want it, but after triggering it two times, it just stops working in Chrome, at least. There are no errors in the console either.

What is going on?

like image 567
Andrew Sun Avatar asked Nov 03 '22 14:11

Andrew Sun


2 Answers

Get rid of the onclick/onend in your HTML and reference the button in your js:

HTML

<button id='tada' sound_url='sounds/tada.mp3'>Tada</button>

And the JS

var sound = function(track){
   $("#playing").append("<audio id='played_audio' src='\" + track + \"' autoplay='true'></audio>");
}

$('#tada').on('click', function () {
   var sound_url = $(this).attr('sound_url');
   sound(sound_url);
});

$('#playing').on('end', 'played_audio', function() {
   $(this).remove();
});
like image 181
Brian Noah Avatar answered Nov 09 '22 06:11

Brian Noah


Okay, lets see..

var audioURL = "http://soundbible.com/mp3/Canadian Geese-SoundBible.com-56609871.mp3";
var audioEl = null;

function removeAudio() {
  if (audioEl && audioEl.parentNode)
    audioEl.parentNode.removeChild(audioEl);
}

function sound() {
  removeAudio();
  audioEl = document.createElement("audio");
  audioEl.src = audioURL;
  audioEl.controls = true;
  audioEl.addEventListener("ended", removeAudio); // <-- Note it's ended, not end!
  document.getElementById("playing").appendChild(audioEl);
  audioEl.play();
}

document.getElementById("tada").addEventListener("click", sound);
<div id="playing">
  
</div>
<button id="tada">Tada</button>

I'm not seeing any problems with this script.

  1. Decide audioURL, set audioEl to null as it will be used later
  2. When the element with ID "tada" is clicked, run our sound function.
    • Remove the audio.
    • Create the audio element.
    • When the audio is finished, remove the audio.
    • Append the audio to the element with ID "playing".
    • Play the audio.

One thing to note is that I use the ended event, not the end event.

(This answer is here because Andrew really wants us to answer it.)

like image 22
Florrie Avatar answered Nov 09 '22 08:11

Florrie