首页 > 解决方案 > 在鼠标点击时从预加载播放随机声音文件(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);

标签: javascriptprocessingp5.js

解决方案


创建一个声音数组并从数组中“选择”一个随机声音:

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.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);
    }
}

推荐阅读