How to click an image to play and audio in html?

Member

by ryleigh , in category: HTML & CSS , 9 months ago

How to click an image to play and audio in html?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 9 months ago

@ryleigh 

To make an image clickable to play an audio file in HTML, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
  <title>Click Image to Play Audio</title>
</head>
<body>
  <h1>Click the image below to play audio</h1>
  <img src="image.jpg" alt="Play Audio" onclick="playAudio()">
  <audio id="audio" src="audio.mp3"></audio>
  
  <script>
    function playAudio() {
      var audio = document.getElementById("audio");
      audio.play();
    }
  </script>
</body>
</html>


In this code, an image is displayed on the webpage and when the image is clicked, the playAudio() function is called which plays the audio file specified in the <audio> tag. Make sure to replace image.jpg and audio.mp3 with the actual path to your image and audio file.