javascript - 在鼠标点击时从预加载播放随机声音文件(mp3 文件)
问题描述
“我想要它,所以当鼠标按下时,它会从代码顶部已经预加载的三个声音文件中播放一个随机声音文件。目前我一次只能播放一个声音文件”
function preload() {
bird = loadSound('kooka.mp3');
bird2 = loadSound('galah.mp3');
bird3 = loadSound('cuckoo.mp3');
}
function setup() {
createCanvas(windowWidth, windowHeight);
background(0);
}
function draw() {
kooka();
}
function kooka () {
if (mouseIsPressed) {
bird2.playMode('untildone');
bird2.play();
bird2.setVolume(0.3);
解决方案
创建一个声音数组并从数组中“选择”一个随机声音:
let sounds = [bird, bird2, bird3];
let randomSound = sounds[Math.floor(Math.random()*sounds.length)];
Math.random()
生成一个介于 0.0 和 1.0 之间的随机数。Math.random()*sounds.length
浮点数 >= 0.0 和 < 也是如此sounds.length
。Math.floor
获取小于或等于数字的整数值。
如果多次按下鼠标按钮,则会播放多个声音。为确保一次只播放一个声音,您必须在变量 ( currentSound
) 中记录当前声音并验证声音是否已完成播放,然后才能开始新声音。
此外,使用mousePressed()
回调而不是内置状态变量mouseIsPressed
。该事件仅在按下鼠标时发生一次,而只要按下鼠标,就会声明变量。例如:
function draw() {
}
let currentSound;
function mousePressed() {
let is_playing = currentSound && currentSound.isPlaying();
if (!is_playing) {
let sounds = [bird, bird2, bird3];
currentSound = sounds[Math.floor(Math.random()*sounds.length)];
currentSound.playMode('untilDone');
currentSound.play();
currentSound.setVolume(0.3);
}
}
推荐阅读
- office-ui-fabric - 如何在流利的 ui react Dropdown 控件中从 API 响应中设置动态选项?
- python - 如何将pickle文件的文件夹转换为单个csv文件
- ios - 无法在 iOS 中连接 firebase crashlytics
- latex - 如何在 LaTeX 中编写标题页?
- javascript - 延迟加载缩略图时阻止 YouTube Cookie
- java - 在 pkcs7 中验证 ECDSA 签名时出错
- amazon-web-services - AWS Key Management Service 散列和加密
- postman - 在预请求脚本中获取环境变量时未解析邮递员嵌套变量
- uipath - UiPath 自动化协助
- java - java.lang.NoSuchMethodError: org.apache.wicket.request.cycle.RequestCycle.find(Ljava/lang/Class;)Lorg/apache/wicket/request/IRequestHandler;