Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
830 views
in Technique[技术] by (71.8m points)

onclick - Play MP3 with when an image is clicked

I want to play an MP3 file when I click a certain image in my site. I also want the MP3 file to be hidden. How can I do that? I tried this code but nothing happens:

<html>
<body>

<script language="javascript" type="text/javascript">
 function playSound(soundfile) {

document.getElementById("dummy").innerHTML=document.getElementById("dummy").innerHTML +
"<embed src=""+mp3/a/bat.mp3+"" hidden="true" autostart="true" loop="false"     />";
 }

<span id="dummy" onclick="playSound('mp3/a/bat.mp3');"><img src="short_a/bat.jpg" 

name="Bottom-1" width="115" height="45" border="0" id="Bottom-1"/></a></span>

</script>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not about PHP, you will just add HTML code to your PHP page.

If you're insistent on embed tag here is the code you want, DEMO

<!DOCTYPE html>
<html>
  <head>
      <script type="text/javascript">
          function playSound(el,soundfile) {
              var embed = document.getElementById("embed");
              if (!embed) {
                  var embed = document.createElement("embed");
                      embed.id= "embed";
                      embed.setAttribute("src", soundfile);
                      embed.setAttribute("hidden", "true");
                  el.appendChild(embed);
              } else {
                  embed.parentNode.removeChild(embed);
              }
          }
      </script>
  </head>
<body>
    <span id="dummy" onclick="playSound(this, 'https://dl.dropbox.com/u/39640025/MP3/Waves.mp3');">
      <img src="short_a/bat.jpg" name="Bottom-1" width="115" height="45" border="0" id="Bottom-1"/>
    </span>
</body>
</html>

Nevertheless I recommend you use Audio API, DEMO

<!DOCTYPE html>
<html>
  <head>
      <script type="text/javascript">
          function playSound(el,soundfile) {
              if (el.mp3) {
                  if(el.mp3.paused) el.mp3.play();
                  else el.mp3.pause();
              } else {
                  el.mp3 = new Audio(soundfile);
                  el.mp3.play();
              }
          }
      </script>
  </head>
<body>
    <span id="dummy" onclick="playSound(this, 'https://dl.dropbox.com/u/39640025/MP3/Waves.mp3');">
      <img src="short_a/bat.jpg" name="Bottom-1" width="115" height="45" border="0" id="Bottom-1"/>
    </span>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...