简体   繁体   中英

How to change Sound file dynamically in p5.js

I just want to load a dynamic sound inside the load. but there is buffer error. it is need to be stopped but then, if stopped, it cant be played.

 let mySound; function preload() { soundFormats('mp3', 'ogg'); mySound = loadSound('assets/doorbell'); } function setup() { let cnv = createCanvas(100, 100); cnv.mousePressed(canvasPressed); background(220); text('tap here to play', 10, 20); } function canvasPressed() { // playing a sound file on a user gesture // is equivalent to `userStartAudio()` mySound = loadSound('assets/othersound'); //<----------LOAD ANOTHER SOUND mySound.play(); }

In your canvasPressed function; reversed these two lines:

mySound.play();
mySound = loadSound('assets/othersound'); //<----------LOAD ANOTHER SOUND

First play the sound that is already loaded (in preload) and THEN load the new sound. It is possible however, with a larger sounds file, or a slow server, that the sound isn't loaded yet when you click the second time. You can always check if it is loaded with mySound.isLoad(). But a more effective way would be doing it like this:

function canvasPressed() {
  // playing a sound file on a user gesture
  // is equivalent to `userStartAudio()`

  mySound = loadSound('assets/othersound', function(){

      mySound.play();

  });      

}

Then you don't have to load anything in preload. In the loadSound() function, the first argument is the url to the sound file, the second argument is the 'succesCallback'. That function runs when the soundFile is loaded and ready to play.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM