简体   繁体   中英

How to stop previous song after clicking next images by using JavaScript

I am Trying to make a simple game like there are so many animals images are there. I want to play a song after clicking on images. I have done that. But problem is after clicking next images the first images song should be stop then next image song will be continued. Here is the sample cide

<!DOCTYPE html>
<html>
<head>
    <title>Anmal Sounds</title>
</head>
<body>
    <script type="text/javascript">
        
     function myAudioFunction(letter) {
        var audio = new Audio('C:\\Users\\SONU\\Desktop\\animal\\'+letter+'.mp3');
         audio.play();
     }
    </script>
    <a onclick="myAudioFunction('tiger');">
     <img src="C:\Users\SONU\Desktop\animal\tiger.jpeg" height="110px" width="110px">
    </a>
    <a onclick="myAudioFunction('cat');">
     <img src="C:\Users\SONU\Desktop\animal\cat.jpg" height="110px" width="110px">
    </a>
    <a onclick="myAudioFunction('elephant');">
     <img src="C:\Users\SONU\Desktop\animal\elephant.jpg" height="110px" width="110px">
    </a>
    <a onclick="myAudioFunction('deer');">
     <img src="C:\Users\SONU\Desktop\animal\deer.jpg" height="110px" width="110px">
    </a>
</body>
</html>

when I click next images the 1st I ages song still continued. But how to stop previous one and play next one

  1. Anyone has any idea

     How to solve this problem.

Have you tried audio.pause() before you reassign the audio variable?

This command may return an error the first time it's done, since audio hasn't been declared yet, but you can fix that by doing if(audio) audio.pause() .

Simple solution you need to put audio object outside like below.

 <script type="text/javascript">
     var audio = new Audio();
     function myAudioFunction(letter) {
        audio.pause()
        audio = new Audio('C:\\Users\\SONU\\Desktop\\animal\\'+letter+'.mp3');
         audio.play();
     }
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM