xxxxxxxxxx
65
// Different sounds
// Jared Donovan 2021
//
// Press the '1', '2', and '3' keys to play/pause three different
// samples. Pressing the same number again will pause the sample
//
// Declare an array to store P5.SoundFile objects
let sounds = [];
// This variable will record which sound file was last playing.
let soundIdx = 0;
function preload(){
// Load the sounds from file
sounds[0] = loadSound('data/one.mp3');
sounds[1] = loadSound('data/two.mp3');
sounds[2] = loadSound('data/three.mp3');
}
function setup(){
createCanvas(150, 150);
}
function draw(){
background(255);
// Display some basic info about which sound,
// and whether it is playing or not.
text("soundIdx: " + soundIdx, 20, 20);
text("isPlaying(): " + sounds[soundIdx].isPlaying(), 20, 40);
}
// When the user presses the key, we check whether it is
// key '1', '2', or '3'. We then use this to decide which
// sound to play. We also need to check whether the user
// is pressing the same key as the sound that is currently
// playing. In this case, we pause/play the sound.
function keyPressed(){
// Make a copy of the old sound index.
let oldSoundIdx = soundIdx;
// If key 1, 2, 3 is pressed, set the sound index accordingly
if (key == '1'){
soundIdx = 0;
} else if (key == '2'){
soundIdx = 1;
} else if (key == '3'){
soundIdx = 2;
}
// Check whether the new sound is different to the old one
// If so, pause the old sound before playing the new one.
if (soundIdx != oldSoundIdx){
sounds[oldSoundIdx].pause();
}
// If the sound is currently playing, pause and vice-a-versa
if (sounds[soundIdx].isPlaying()){
sounds[soundIdx].pause();
} else {
sounds[soundIdx].loop();
}
}