简体   繁体   中英

p5.js sound library: how to add/remove p5. Phrases() from p5. Part()?

I am working on a p5.js with sound library, and using p5 Phrase and p5 Part for making multiple sound files play at once.

I was able to addPhrase() but the removePhrase() function inside the mousePressed function does not work at all. How can I toggle between adding and removing phrases from the p5 Part, which would turn on/off the specific sound file?

var box, drum, myPart;
var drumPhrase;
var boxPhrase;
var boxPat = [1, 0, 0, 2, 0, 2, 0, 0];
var drumPat = [0, 1, 1, 0, 2, 0, 1, 0];

function preload() {
    box = loadSound('sound/noise.mp3');
    drum = loadSound('sound/drum1.wav');
}

function setup() {
    noStroke();
    fill(255);
    textAlign(CENTER);
    masterVolume(0.1);

    boxPhrase = new p5.Phrase('box', playBox, boxPat);
    drumPhrase = new p5.Phrase('drum', playDrum, drumPat);
    myPart = new p5.Part();

    myPart.addPhrase(boxPhrase);
    myPart.addPhrase(drumPhrase);

    myPart.setBPM(60);
    masterVolume(0.1);

    myPart.start();

}

function draw() {
    background(0);    
}

function playBox(time, playbackRate) {
    box.rate(playbackRate);
    box.play(time);
}

function playDrum(time, playbackRate) {
    drum.rate(playbackRate);
    drum.play(time);
}

function mousePressed() {
    myPart.removePhrase(box);

}

You're right, there is a bug in p5.sound so that p5.Part.removePhrase does not work.

Here's a fix: Add the following snippet at the end of your setup() function:

p5.Part.prototype.removePhrase = function (name) {
    for (var i in this.phrases) {
        if (this.phrases[i].name === name) {
            this.phrases.splice(i, 1);
        }
    }
};

This replaces the buggy function with the actual working code.

I'll let the p5.js developers know so that the bug can be fixed in the official version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM