scopa scopa - 1 month ago 20
Javascript Question

Play audio onclick

I have a simple website I am trying to build. I have a mp4 video (it is a sign no audio)
I want to click the video and have it play an mp3 w/ controls. Just cannot figure out how to do this.

Assume I could use something like this:

<audio controls id="linkAudio">
<source src="demo.ogg" type="audio/ogg">
<source src="demo.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

<script>
document.getElementById("link_id").addEventListener("click", function () {
document.getElementById("linkAudio").play();
});
</script>


But where do I reference the video src as the thing to click?

Thanks

Answer

You could have the <video> separate and on click event trigger the audio.

document.getElementById("link_id").addEventListener("click", function () {
  document.getElementById("linkAudio").play();
});
video{
  width: 200px;
  display: block;
}
<video src='http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4' id='link_id'></video>

<audio controls id="linkAudio">
  <source src="http://www.noiseaddicts.com/samples_1w72b820/29.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

Comments