How to play sounds in p5.js?

Member

by brandy , in category: Javascript , 3 days ago

How to play sounds in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 2 days ago

@brandy 

In p5.js, you can play sounds by using the p5.sound library.


Here is a simple example:

  1. First, make sure you have included the p5.sound library in your HTML file:
1
2
<script src="https://cdn.jsdelivr.net/npm/p5"></script>
<script src="https://cdn.jsdelivr.net/npm/p5/lib/addons/p5.sound.js"></script>


  1. In your p5.js sketch, you can load a sound file using the loadSound() function:
1
2
3
4
5
let soundFile;

function preload() {
  soundFile = loadSound('path-to-your-sound-file.mp3');
}


  1. You can then play the sound using the play() method:
1
2
3
4
5
6
function setup() {
  createCanvas(400, 400);
  
  // Play the sound when the sketch starts
  soundFile.play();
}


You can also stop the sound using the stop() method, pause it using the pause() method, or change its volume using the setVolume() method.


Remember to check the console for any errors and make sure your sound file path is correct.