caderao
caderao

Reputation: 1

How to play audio when clicking on a image?

I have a school project where I can't use Java, just HTML and CSS. The theme is Lucky Luke, and I'm trying to make audio play when clicking on a image.

The idea is to play the audio when I click on an image.

<div id="luckyShoot">
    <img src="images/lucky_luke_shooting.png">
</div>

<div id="song"> 
    <audio>
    <source src="audio/soundtrack.wav" type="audio/wav">
    </audio>
</div>

Upvotes: 0

Views: 1280

Answers (2)

Kiran Mistry
Kiran Mistry

Reputation: 2725

Interesting question.

This is your solution

Example and Demo:

The following code will make a click on the image and play a sound of a horse, as long as you test it in a Chrome browser.

div#lH {
  position: absolute;
  width: 30px;
  height: 30px;
  overflow: hidden;
  z-index: 1;
  font-size: 25px;
  text-align:center;
}
audio#aH {
  position: absolute;
  top: -5px;
  left: -5px;
  z-index: 2;
  opacity: 0.01;
}
 <div id="lH">
<audio controls id="aH">
  <source src="http://www.w3schools.com/html/horse.ogg" type="audio/ogg">
  <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<img src="https://static.rfstat.com/bloggers_folders/user_50017/my_media/184c7a0c-9df2-451e-8e4b-759c30eb5453.png" />
</div>

you can edit or preview code Here on JSFiddle

Upvotes: 1

siddesh
siddesh

Reputation: 41

let audio = document.getElementById("myAudio")

function playMySong(){
    if(audio.paused){
        audio.play()
    } else {
        audio.pause()
    }
}
img {
    width:250px;
    height:250px;
    cursor:pointer;
}
<div id="luckyShoot">
    <img src="https://static.rfstat.com/bloggers_folders/user_50017/my_media/184c7a0c-9df2-451e-8e4b-759c30eb5453.png" onClick="playMySong()">
</div>

<div id="song"> 
    <audio id="myAudio" controls>
        <source src="https://www.computerhope.com/jargon/m/example.mp3" type="audio/mp3">
    </audio>
</div>

Upvotes: 0

Related Questions