javascript - 单击鼠标从预加载播放随机声音文件(mp3 文件)

标签 javascript processing p5.js

“我想要它,所以当按下鼠标时,它会从代码顶部预加载的三个声音文件中随机播放一个声音文件。目前我一次只能播放一个声音文件”

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 是一个 float >= 0.0 和 <sounds.lengthMath.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);
    }
}

关于javascript - 单击鼠标从预加载播放随机声音文件(mp3 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58569754/

相关文章:

javascript - jquery在任何情况下都有if语句触发

java - 处理Java,如何切换全屏?

javascript - 在半径范围内拾取食物对象

javascript - 如何解决使用 p5 创建板的问题

javascript - 计算绳索的长度和一个奇怪的结果

javascript - 将 p5js 添加到 Ember 应用程序

javascript - JS : How to pass selected data to the next page?

javascript - 用于验证和 es 6 的 Gulp 工作流

javascript - 将变量从 javascript 输出到 HTML 成本表中

javascript - 尝试画一个书架(可汗学院练习)