Image to play sound onclick

早过忘川 提交于 2021-01-28 07:41:57

问题


I'm trying to make a song play when I click on an image. everytime I do it using the solutions on the here Either the image doesn't show, the audio doesn't play, or both. I don't understand what my issue is and could use any help.

My HTML `

<head>
<link rel="stylesheet" type="text/css" href="main.css">
<meta charset="utf-8">
<title>#F7D64B</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="stylesheet" type="text/css"                 
href="https://csshake.surge.sh/csshake.min.css">
</head>

<body>
<script>
var audio = new Audio('Music/song.wav');
    function myAudioFunction
<script>

<center>

<audio id="audio" src="Music/song.wav"></audio>
<a onclick="document.getElementById("audio").play();">
    <img src="assets/a.png" width=550 height=550 class="shake-slow shake-    
constant">
</a>
</center>

</body>

<footer>
<!-- art by @woun404-->
<!-- #F7D64B -->
</footer>
</html>`

回答1:


Here's a working example:

document.getElementById('play').addEventListener('click', function (e) {
  e.preventDefault();
  document.getElementById('audio').play();
});
<audio id="audio" src="http://www.soundboard.com/handler/DownLoadTrack.ashx?cliptitle=Never+Gonna+Give+You+Up-+Original&filename=mz/Mzg1ODMxNTIzMzg1ODM3_JzthsfvUY24.MP3"></audio>

<a href="#" id="play">
    <img src="assets/a.png" width=550 height=550 class="shake-slow shake-    
constant">
</a>



回答2:


Using JavaScript only would look like this:

<body>  
<center>

<audio id="audio" src="Music/song.wav"></audio>
<img id="img" src="assets/a.png" width=550 height=550 class="shake-slow shake-    
constant">
</center>
<script>
document.getElementById("img").addEventListener("click", function(){
    document.getElementById("audio").play();
});
<script>
</body>

It is advised to use JavaScript for big projects since it works way faster.



来源:https://stackoverflow.com/questions/49539491/image-to-play-sound-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!