htmlaudio

How to play an audio file in the background after clicking a link? (no embed)


Currently I am using following code to play some audio after a link is clicked:

<a href="http://somehost.com/word_audio.ogg">Pronunciation of a word</a>

For now if the user clicks on the link, a new page with an audio playing panel is loaded. After playing the audio, the user has to click GO BACK button of the browser to get back to the original content.

Is it possible to play the audio without being directed to a new page? When the user clicks on the link, the audio just plays in the background? (Don't want to use embed because it's just a 1 second audio for a word's pronunciation as a minor explanation of an uncommon word).


Solution

  • Actually the href attribute is redirecting you to the new page, you can use e.prevenDefault() in the link click event handler to stop this redirection and create a dynamic audio element with this href as source and play it.

    This is what you need:

    function playItHere(e, link) {
      var audio = document.createElement("audio");
      var src = document.createElement("source");
      src.src = link.href;
      audio.appendChild(src);
      audio.play();
      e.preventDefault();
    }
    <a href="https://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg" onclick="playItHere(event, this)">Pronunciation of a word</a>