I am trying to get background music playing behind my game using p5.js.
However, I have tried every variation I can possibly think of, trying new Audio, not having preLoad, etc. And whatever I do I still get the
Uncaught TypeError: Cannot read property ‘play’ of undefined” on my backgroundMusic.play();
I have tried to follow what the p5.js reference
says to do.
let backgroundMusic; function preLoad(){ backgroundMusic = loadSound("music.mp3"); } function setup() { createCanvas(600, 360); backgroundMusic.play(); backgroundMusic.setVolume(10); }
Advertisement
Answer
you need to call preLoad() method inside the setup() to assign backGroundMusic.
let backgroundMusic; function preLoad(){ backgroundMusic = loadSound("music.mp3"); } function setup() { createCanvas(600, 360); preLoad(); //added backgroundMusic.play(); backgroundMusic.setVolume(10); }