replit / kaboom

💥 JavaScript game library
https://kaboomjs.com
MIT License
2.59k stars 225 forks source link

Improve sound control #33

Closed khromov closed 3 years ago

khromov commented 3 years ago

👋 I'm making a proof of concept of a rhythm game using Kaboom. It's such a simple and easy-to-understand engine & it's great to work in.

It would be very useful to have additional control of the play() function, mainly:

  1. Being able to ask the underlying player how long it has been playing:
const music = play("song1");
//...
music.currentTime();
  1. Being able to attach event listeners to the audio timeupdate event and other events from the underlying audio player so you don't have to poll for updates, similar to obj.on()

const music = play("song1");
//...
music.on("timeupdate", () => {
    //...
});
slmjkdbtl commented 3 years ago

Looks like these are 2 features by the DOM media elements, the currentTime() could be trivial to implement, but I'm not too sure on what's the mechanism of "timeupdate" being fired, on DOM media elements currentTime seem do seem update in between "timeupdate" events

khromov commented 3 years ago

@slmjkdbtl Exactly, these are two features of HTMLMediaElement. timeupdate triggers very frequently but depends a bit on system load, if the tab is idle and other factors. There is a good explanation in the MDN documentation.

I see that you are using AudioBufferSourceNode. There is some discussion on StackOverflow around how to handle counting the current time that might be useful.

I think having currentTime() would be sufficient, since you can just poll the time using obj.on("update" ... from another object!

slmjkdbtl commented 3 years ago

Added as .time() in b1ce721 and this example!

khromov commented 3 years ago

@slmjkdbtl Looks great! In the audio example you linked, pausing with spacebar doesn't seem to work for me on Firefox 88. It works in Chrome.

slmjkdbtl commented 3 years ago

Hmm so Firefox doesn't like setting playbackRate to 0 as a hacky audio pause, thanks for letting me know, I'll try something else for pausing!

slmjkdbtl commented 3 years ago

Fixed Firefox pausing issue in 1fe8d0a. Closing this for now, feel free to reopen if there are other audio related feature requests or discussions!