点击图片播放MP3

3

当我点击网站上的某个图片时,我希望能够播放一个MP3文件。同时,我也想让这个MP3文件隐藏起来。我该如何实现呢?我尝试了以下代码,但没有任何反应:

<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>

你可以使用 iframe,在点击时将 iframe 的 src 设置为自动播放 mp3 的页面,使用 CSS 或其他方式将 iframe 隐藏。 - 99823
这里正是你想要的,演示 - Okan Kocyigit
ocanal- 这个可以用不同的形式来写吗? - Reden Villaflores Efondo
那个是用Audio Object编写的,这是播放声音最有效的方式。 - Okan Kocyigit
我该如何做到这一点?我使用的是 PHP 语言,你能教我吗? - Reden Villaflores Efondo
"<embed src=\""+mp3/a/bat.mp3+"\" hidden=\"true\" autostart=\"true\" loop=\"false\"/>" 是语法错误。URL 需要放在引号内。 - mcrumley
1个回答

11

这不是关于PHP的问题,你只需将HTML代码添加到PHP页面中。

如果您坚持要嵌入标记,请使用以下代码:演示

<!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>

尽管如此,我仍建议您使用音频API,演示

<!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>

太棒了!真的帮助了我解决了我的Angular指令问题。 - Scott Yu - builds stuff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接