【问题标题】:Random selection of audio files (onclick effect)随机选择音频文件(点击效果)
【发布时间】:2014-11-27 05:24:18
【问题描述】:

我已经成功地为我的点击计数器图像添加了 onclick 音频效果,但我想知道,有没有办法随机选择声音,而不是一个声音?当我点击我的图片时,会出现点击图片的次数,并播放声音,但我希望它在每次点击时播放不同的(随机)音频文件(来自我的选择)

这些是到目前为止我的按钮的脚本

Javascript

function clickCounter(){
     var audio = document.getElementById("audio");
     audio.play();
     if(typeof(Storage)!=="undefined"){
         if (localStorage.clickcount)
         {
             localStorage.clickcount=Number(localStorage.clickcount)+1;
         }
         else
         {
             localStorage.clickcount=1;
         }
         document.getElementById("result").innerHTML="<center><b>You have clicked the poop
         </b>"+ localStorage.clickcount + "<b> times!</b></center>";
     }
     else{
         document.getElementById("result").innerHTML="I'm sorry to inform you that your browser
         does not support this web storage... I guess you could say that your browser is...
         shit! awwww yeaahh!";
     }
     cursor: pointer;
}

HTML

<center>
     <font face="chiller" color="#603913" "font size="300" <align="center"><b>Click the
     poop!</b>
</center>
<center>
    <p><picture onclick="clickCounter()"><picture
     onmouseover="document.getElementById('touch').play()"><img src="poop.png"></button></p>
</center>
<audio id="audio" src="fart-01.wav"></audio>
<audio id="touch" src="sticky goo.wav"></audio>
<div id="result"></div>

我将如何编写这个脚本?我知道我必须将它与我当前的 onclick 函数交织在一起,而且我必须制作一个表格,可能带有 tr 或 td 标签。有人可以帮我吗?我不能让它工作。

提前感谢大家!

【问题讨论】:

  • 是什么让您认为需要添加表格? (我问是因为我认为我误解了你的部分问题。)
  • 我的 IT 老师说可以这样工作。就我自己而言,我对整个脚本感到非常困惑
  • 作为理解脚本的一般策略,尝试将不理解的部分删去简化,看看你认为自己理解的部分是否仍然有效。如果脚本不是您自己编写的,而是被交给了家庭作业,您真的应该向我们解释一下:这样可以更轻松地帮助您(如果可以的话)。

标签: html audio random onclick click-counting


【解决方案1】:

您可以为此使用开关盒。

你生成一个随机数,例如

var number = Math.floor((Math.random() * 3) + 1);

然后您可以使用开关盒从您使用随机数生成的 N 种可能性中选择一种随机声音。

喜欢

函数 setSound() {

    switch (number) {
    case 1:
        setSound1;
        return sound;
        break
    case 2:
         setSound2;
        return sound;
        break
    case 3:
         setSound3;
        return sound;
        break
    }
}

然后将返回值添加到您要播放声音的代码中。

在这种情况下,您需要返回您从 swtich 案例中随机选择的声音文件的名称。

【讨论】:

  • 我理解这个概念,它很棒!但我不确定如何将它编写成我已经拥有的内容。我是在 setSound1 之后写我的 src 吗?还是我使用 document.GetElementById("my_audio_file")?什么是回声?我需要那个做什么?对不起,我对脚本很陌生
  • 您可以设置一个文件名 (setSound1) 然后返回声音的名称,然后像 src="soundName" 中的变量一样使用它。或者你可以使用document.getElementById('yourAudioTag').play()。也许这个链接会有所帮助storiesinflight.com/html5/audio.html
  • 你能用 jsfiddle 做这个吗?或者也许给我发一封带有 html 文件的邮件,其中包含你所拥有的内容?我的电子邮件是 Daniel_Romar@hotmail.com。谢谢你的帮助! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
相关资源
最近更新 更多