Load and Play Sound
Load sound during preload(). Play a sound when canvas is clicked.
To run this example locally, you will need the
p5.sound library
a sound file, and a running local server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let song;
function setup() {
song = loadSound('assets/lucky_dragons_-_power_melody.mp3');
createCanvas(720, 200);
background(255, 0, 0);
}
function mousePressed() {
if (song.isPlaying()) {
// .isPlaying() returns a boolean
song.stop();
background(255, 0, 0);
} else {
song.play();
background(0, 255, 0);
}
}