我是一个完全的新手在这个东西,但我希望有一个随机设置的4音调连续播放时,按键5被点击.....
我对数组、Math.random、setInterval...有一个基本的了解。但是我迟钝的大脑不能围绕着如何让事情变得如此简单。任何指向正确方向的指针都将不胜感激。
我所拥有的就是让声音单独触发的代码.
$("document").ready(function() {
$(".button_1").click(function () {
$('#sound-1').get(0).play();
});
$(".button_2").click(function () {
$('#sound-2').get(0).play();
});
$(".button_3").click(function () {
$('#sound-3').get(0).play();
});
$(".button_4").click(function () {
$('#sound-4').get(0).play();
});
$(".button_5").click(function () {
$("????").get(0).play();
});
});发布于 2015-09-05 08:10:49
下面是如何播放单个随机声音。您可以对1到4之间的数字使用Math.floor(Math.random() * 4) + 1,并执行"#sound-"+randNum
$(".button_5").click(function () {
ranNum = Math.floor(Math.random() * 4) + 1;
$("#sound-"+ranNum).get(0).play();
});要连续播放多首随机歌曲,您可以使用setInterval(),并跟踪它运行了多少次,然后在运行完成时使用clearInterval():
$(".button_5").click(function () {
var plays = 4; // Play 4 sounds, each a second apart.
var timer = setInterval(function(){
ranNum = Math.floor(Math.random() * 4) + 1;
$("#sound-"+ranNum).get(0).play();
plays--;
if(plays < 1) clearInterval(timer);
}, 1000);
});只需注意,它可以重复一个声音,如果你不想重复,你需要跟踪播放的声音。
最后,您可能需要确保在播放完声音之前不能再次单击该按钮。执行此操作的基本方法是disable按钮,直到间隔结束:
$("#button_5").click(function () {
var plays = 4;
var self = this;
$(self).prop( "disabled", true );
var timer = setInterval(function(){
ranNum = Math.floor(Math.random() * 4) + 1
$("#sound-"+ranNum).get(0).play();
plays--;
if(plays < 1) {
clearInterval(timer);
$(self).prop( "disabled", false );
}
}, 1000);
});。请注意,在示例中,我只是执行console.log("#sound-"+ranNum),以显示将播放的内容。
发布于 2015-09-05 08:22:05
你应该有一个播放声音的函数,然后调用它四次。
function playSound(number){
$('#sound-' + number).get(0).play();
}
$(".button_5").click(function () {
var tones = 1;
var t = setInterval(function(){
if(tones>=4) clearInterval(t);
playSound(Math.floor((Math.random() * 4) + 1));
tones++;
}, 1000);
});在这里拉小提琴http://jsfiddle.net/roanrj6e/
https://stackoverflow.com/questions/32408139
复制相似问题