简体   繁体   English

如何在 p5.js 中动态更改声音文件

[英]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;在你的画布中按下 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().您可以随时检查它是否加载了 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'.在 loadSound() function 中,第一个参数是声音文件的 url,第二个参数是 'succesCallback'。 That function runs when the soundFile is loaded and ready to play. function 在加载声音文件并准备播放时运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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