xxxxxxxxxx
93
/*
Adapted from Cassie Tarakajian 🙏
https://editor.p5js.org/cassie/sketches/H75F64z2f
And: https://p5js.org/reference/#/p5.SoundLoop
Tempo (BPM) ranges for musical genres
https://learningmusic.ableton.com/make-beats/tempo-and-genre.html
Tone.Time convention to encode intervals as strings
https://github.com/Tonejs/Tone.js/wiki/Time
BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...see link above)
*/
let clap;
let clapPattern = [1, 0, 0, 0, 1, 0, 0, 0];
let clapIndex = 0;
let loop;
let bgHue = 0
function preload() {
clap = loadSound('clap.wav');
}
function setup() {
colorMode(HSB);
let cnv = createCanvas(400, 400);
cnv.mousePressed(togglePlayback);
button = createButton('Randomize Pattern');
button.mousePressed(randomize);
loop = new p5.SoundLoop(onLoop, "8n");
console.log("Original pattern:", clapPattern)
}
function draw() {
background(bgHue, 50, 100);
textSize(18)
text('tap to start/stop playback', 20, 40);
}
function onLoop(interval) {
// if value of index position in pattern array is 1,
// then play the clap file at the specified interval
if (clapPattern[clapIndex] === 1) {
clap.play(interval)
}
// iterate through clapPattern index positions
clapIndex = (clapIndex + 1) % clapPattern.length;
// Try changing the tempo!
loop.bpm = 120;
}
// this function runs when canvas is pressed
function togglePlayback() {
// ensure audio is enabled
userStartAudio();
if (loop.isPlaying) {
loop.stop();
} else {
loop.start();
}
}
function randomize() {
clapPattern = getPattern(clapPattern.length)
console.log("New pattern!", clapPattern)
}
function getPattern(length) {
// update the background for visual feedback
bgHue += 30;
if (bgHue > 360) bgHue = 0;
// create an empty array
// for as many times as the num positions in array
// get a random value from 0 to 1
// and store that value in pattern array
let pattern = [];
for (let i = 0; i < length; i += 1) {
let value = int(random(0, 2));
pattern.push(value);
}
// return the array to variables in randomize function
return pattern;
}