在Wordpress网站的图像点击上播放随机声音

Play random sound on image click in Wordpress site?

本文关键字:播放 随机 声音 Wordpress 网站 图像      更新时间:2023-09-26

好吧,所以我已经研究了几个小时了,现在我可能只是更困惑自己。)

我在这里阅读了这个问题的答案:如何在网页中点击时播放随机声音?

我之前也读过那个作者最初引用的源代码。

我在Wordpress网站上的header.php文件的标签之间添加了以下代码:

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function playSounds() {
  var sounds = new Array(
    "http://www.namechanged.com/laughs/laugh1.wav",
    "http://www.namechanged.com/laughs/laugh2.wav",
    "http://www.namechanged.com/laughs/laugh3.wav",
    "http://www.namechanged.com/laughs/laugh4.wav"
   );
$("#element").html("<embed src='""+sounds[Math.floor(Math.random()*(sounds.length+1))]+"'" hidden='"true'" autostart='"true'" />");
}
</script>

然后我把这个添加到我的身体标签上:

onload="javascript:playSound()"

在我的身体标签之间:

<div id="element">
<button onclick="playSound()">LAUGH</button>
</div>

我知道我错过了一些显而易见的痛苦,但我想我已经看了太久了,从来没有看到它是什么。救命?

如果你要在网页上使用声音,那么我真的建议你使用Soundmanager库。它肯定会消除在你的页面上使用声音的所有痛苦。

然后添加你的声音按钮点击将是非常容易的!

已编辑:我修复了函数调用,并从中删除了+1,因为它导致有时会得到索引4,而索引4在数组中不存在,并导致div具有undefined src属性。我还将按钮放在div之外,因为它被embed标记所取代。请在您的代码中复制此示例,并包含相同的DOCTYPE,看看它是否有效:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script>
        function playSounds() {
            var sounds = new Array(
    "http://www.faenathara.com/laughs/Natharalaugh1.wav",
    "http://www.faenathara.com/laughs/Natharalaugh2.wav",
    "http://www.faenathara.com/laughs/Natharalaugh3.wav",
    "http://www.faenathara.com/laughs/Natharalaugh4.wav"
   );
            var index = Math.floor(Math.random() * (sounds.length));
            $("#element").html("<embed src='"" + sounds[index] + "'" hidden='"true'" autostart='"true'" />");
        }
    </script>
    <title></title>
</head>
<body onload="javascript:playSounds()">
<button onclick="playSounds()">
            LAUGH</button>
    <div id="element">
    </div>
</body>
</html>

这在Chrome、Firefox和IE9中对我来说完全可以。

Hanlet。