Gaweph / p5-typescript-starter

Base starter project using p5js and typescript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use sound

ihateids opened this issue · comments

It is very nice work, I am just struggling to use sound via loadSound. I am unable to get it working with the starter. Any idea, please ?

There is currently some missing global typings with regards to the sound and dom addons.

// won't work 
mySound = loadSound('assets/doorbell');

// try this instead
mySound = new p5.SoundFile('assets/doorbell');

Documentation here: https://p5js.org/reference/#/p5.SoundFile

More information on the issue here: p5-types/p5.ts#16

Hope this helps. Let me know if you need more information :)

Thank you for the quick update. I tried the proposed solution, but it has a small drawback. The 'new p5.SoundFile' will load the sound in an asynchronous manner. It requires a callback to capture an event that the sound has been loaded.

The issue is, that after calling 'new p5.SoundFile', code will continue with P5 setup and draw function. If I want to play the sound in the setup function, for instance, the sound may not be loaded yet and the whole code breaks. I want to use it in preload function and trying to 'Promise'-fy it somehow did not work for me.

Since my aim is to use/share publicly available examples of how to use sound in P5, is there any suggested way how to preload sound without tricky hacks while using the suggested 'new p5.SoundFile', please?

this might get resolved soon.
There are a couple of PRs that relate to this.
processing/p5.js#5569
DefinitelyTyped/DefinitelyTyped#58331

@ihateids I think that the loadSound works in the same way. In the p5 documentation is suggests putting the method inside the preload function

function preload() {
    mySound = new p5.SoundFile('assets/doorbell')
}

I think this is what you're looking for.

Unfortunately not. Let me try to depict the issue with a screenshot from firefox console:

image

and here is sample code:

let sound: p5.SoundFile;

function soundLoaded() {
  console.log('Sound loaded');
}

// P5 will call this function to preload any assets (sounds, sprites, etc) and will continue with setup only when finished
function preload() {
   sound = new p5.SoundFile('assets/ding.mp3', soundLoaded);
   console.log('Preload finished');
}

function setup() {
  console.log("🚀 - Setup initialized - P5 is running");
  createCanvas(windowWidth, windowHeight);
  sound.play();
}

@ihateids for now maybe just define he missing method at the top of your sketch.ts file.

declare function loadSound(path: string): p5.SoundFile;

Let me know how you get on.

oh yes, that is the hack needed. Thank you so much for your help :)