Getting the exact audio time (in seconds) reguadless of compression/platform

I'm working on a project where I must sync events eactly to the time of the playing audio track.

I've found that if I take AudioSource.time I can get just that. On the PC build everything is running perfectly in sync with that value. However it clearly states in the documnetation that...

"Be aware that: On a compressed audio track position does not necessary reflect the actual time in the track Compressed audio is represented as a set of so-called packets. The length of a packet depends on the compression settings and can quite often be 2-3 seconds per packet. See Also: timeSamples variable."

The same code running on the Mac build is compleatly out of sync and AudioSource.time does not appear to be giving the exact values. It seems to indicate that I'll be able to use timeSamples to get more accurate timing but it is not clear to me how I can convert this into a value in eplased seconds (I also need to go the other way and be able to seek to exact time in seconds into the audio track).

3 Answers

3

Just divide timeSamples by the sampling rate, (which you can get from the poorly-named AudioClip.frequency if you need to). Store the inverse of the sampling rate if you don't want to divide a lot, for performance. timeSamples samples * (1 second / frequency samples) = timeSamples / frequency seconds.

http://en.wikipedia.org/wiki/Sampling_rate#Audio

If it were me, I'd probably just start a manual timer every time I played the audio file to avoid any issues like this. Alternatively, you could convert everything to uncompressed tracks (wav).

Use AudioClip.length to get the duration in seconds or AudioClip.samples to get it in samples.