Add "[time position v] of sound [sound v]" feature

I am wanting to create a rhythm game, and uh...I can't do that too accurately without being able to return the time position of a song.

This is a bit tough to implement, because Snap! actually lets multiple instances of a sound play at once - try clicking the "play sound (sound)" block several times in quick succession!

If you'd like to do this yourself with the JS function block, try out this code:

"call (JavaScript function (sound) { ... }) with inputs (item 1 of (my (sounds)))"

Here's the code in the JS function block, to copy and paste:

const stage = this.parentThatIsA(StageMorph);
const audio = stage.activeSounds.find(aud => aud.src === sound.audio.src);
if (audio) {
  return audio.currentTime;
} else {
  return 0;
}

According to my (not extremely rigorous) testing, this finds the most recent instance of that sound being played, and returns its current time (in seconds).

1 Like

you could also try to use the microphone to analyze the song, e.g. by looking at how the volume peaks...

Or you could cheat. If you know how long your song is, just create a separate timer that runs in parallel.

1 Like

Bad idea. I did this in Scratch and it WILL get off by a few milliseconds-seconds. If you are doing a rhythm game, ALWAYS use the audio position, or else have some kind of delta-time setup where framerate doesn't matter at all, anyway.

if you synchronize music it's best to run the project in turbo mode, both in Scratch and Snap, because turbo increases the ticking resolution.