@mac
To change a sound file dynamically in p5.js, you can use the loadSound()
function to load different sound files based on user input or any other criteria. Here's an example code snippet that demonstrates how to dynamically change a sound file in p5.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
let sound; function preload() { sound = loadSound('sound1.mp3'); } function setup() { createCanvas(400, 400); // Play the initial sound file sound.play(); } function keyPressed() { // Change the sound file when a key is pressed // Stop the current sound sound.stop(); // Load and play a new sound file based on key pressed if (key === '1') { sound = loadSound('sound1.mp3'); } else if (key === '2') { sound = loadSound('sound2.mp3'); } else { sound = loadSound('defaultSound.mp3'); } // Play the new sound file sound.play(); } |
In this example, we first load an initial sound file in the preload()
function. When a key is pressed, we stop the current sound, load a new sound file based on the key pressed, and play the new sound file. You can modify this code to change the sound file dynamically based on any other criteria as needed.