Accurate timer for music?

For context, I’m working on a music game that recognizes the players’ button inputs based on divisions of the beat. Since obviously the accuracy of time of the input really matters here, it seems like the time.delta parameter will not be terribly helpful, since it drifts with how long it takes to render frames.

So I suppose overall this is a two part question:

1.) Is the only option for accuracy then to figure out the math associated with beats per measure, using the sample count provided with audio.timeSamples? (And, I’m assuming boosting the priority level of the game object that’s playing the sound.)

2.) Most of the examples for timers I’m seeing online at this point don’t seem like they have a start/stop/restart control associated with them, and seem to be based on the delta time. For simplifying the divisions, I need (well, would much prefer) to have a timer that can be reset each bar and be referenced by outside functions. Is there one that exists that I haven’t encountered yet?

I’m still perusing through the documentation and forums, but haven’t found a timer yet that seems like it’ll be accurate AND able to be referenced and reset; I’ve made this system work in a different coding language, just trying to translate it into an functioning system in C#. Figured I’d ask while I continue the hunt. :slight_smile:

Thanks!

Skruff

1 Answer

1

C# (all .Net languages, actually) comes with a timer that’s highly accurate. It’s called Stopwatch.

Its accuracy depends on the individual machine, but it’s in the nanoseconds and will be more than sufficient for your purpose. One of its most used properties is the ElapsedMilliseconds, but if you need something below milliseconds, you can use the ElapsedTicks property and the Frequency property to convert it into a (high precision) number of seconds.

Stopwatch can be referenced as you please and has all the methods you describe and which are usually attributed to a stopwatch, e.g. Start, Stop, Reset.

Good comment, and good solution. :) I've also +1'ed your initial question as it was well-written and easily understandable.