I’m building a rhythm game in TypeScript, and I need to let the user upload a sound file, load it, and then play it on demand. I know this is possible in vanilla JS, but I want to do it “the P5 way” so my code is cleaner. Below is a minimal example of what I’m trying to do. I expected loadSound to work, but it’s not even an available method, and the p5 examples online don’t address this use case. Am I missing something, or does this have to be a feature request?
let p: p5 = myP5SketchInstance;
p.createFileInput(handleAudioFileInput);
function handleAudioFileInput(file: p5.File) {
let p: p5 = myP5SketchInstance;
let song = p.loadSound(file);
}
If you are wanting to use p5 then you can use the drop()
method and callback the loadSound()
method. Then in the success callback of the loadSound()
method, play the sound …
function setup() {
let cnv = createCanvas(400, 400);
background(222);
cnv.dragOver(_ => {
background(157);
});
cnv.dragLeave(_ => {
background(222);
});
cnv.drop(file => {
let snd = loadSound(file.data, _ => {
snd.play();
p.html('playing').position(125, 100);
});
}, _ => {
background(222);
});
let p = createP('Drag your file here ...').position(25, 100).style('font-size', '27pt');
}
Sorry, just realized you were using the createFileInput()
method …
function setup() {
...
createFileInput(file => {
let snd = loadSound(file.data, _ => {
snd.play();
});
});
}