简体   繁体   中英

p5.js sound and keyTyped or keyPressed function

I'm trying to write a code where when I press a certain keyboard key, a sound will play. I'm using p5.js and have tried the keyTyped() function and keyPressed() function but it's not working. By not working, I meant there is nothing wrong with the code that I've typed because it can be played but no sound is produced when i click on the A key. The code I used Function keyTyped () {

if ( key === ‘a’) {

keyA.play ( ) }

}

The following works on my system. Make sure that you have a folder called 'assets' and that you have dragNdropped a file called 'keyA.mp3' into it. I used a Chrome browser on a Mac. Important: click on the gray window first, then type 'a' from your keyboard and it should work.

function preload(){
  sound = loadSound('assets/keyA.mp3');
}

function draw() {
createCanvas(displayWidth, displayHeight);
background(209);
}

function keyTyped() {
  if (key == 'a') {
    sound.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