单键播放随机声音 [英] Play a random sound on single button
问题描述
首先,我首先要说我是您遇到过的最糟糕的编码器.我正在尝试制作一个Javascript,该Javascript可让我按下一个按钮并随机播放声音.我的想法是随机进行数学运算,并让一个数字与一个声音相对应,然后发出一个if语句播放.我真的不知道从这里去哪里.实际上我什至不知道我是否做对了.
First, I shall start off by saying I am the worst coder you will ever meet. I'm trying to make a Javascript that allows me to press a single button and have a random sound play. My idea was to do a math random and to have a number correspond with a sound that would then do an if statement that would play. I really have no idea where to go from here. I actually have no idea if I'm even doing this right.
我的Javascript
My Javascript
function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
var sounds = ["sound1", "sound2", "sound3", "sound4", "sound5", "sound6", "sound7", "sound8", "sound9", "sound10"];
sound1 = 1;
sound2 = 2;
sound3 = 3;
sound4 = 4;
sound5 = 5;
sound6 = 6;
sound7 = 7;
sound8 = 8;
sound9 = 9;
sound10 = 10;
sound1.src = "sound1.mp3";
//And so on of the sound files
}
我的HTML
<button onclick="mySounds()">Click for a sound</button>
<p id="Sounds"></p>
推荐答案
您可以按照以下链接中的方法使用play(). W3学校
You can use method play() as in the following link. W3 Schools
我认为最好使用Math.random()方法.就像在下面的代码中一样,您可以定义最大值和最小值.
And I think it's better if you go with Math.random() method. As in the followoing code you can define a max and min value.
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
在您的情况下,最小值为0,最大值为数组中最后一项的索引.这应该做.
The min number in your case would be 0 and max would be last item's index in your array. This should do it.
如果直接更改数组项,则指向声音的链接甚至会更短.
And if you change your array items directly the links to the sounds your code would even be shorter.
这篇关于单键播放随机声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!