- Home /
Problem using AudioSource.timeSamples
I'm trying to sync game events to audio beats, and I'm trying to use AudioSource.timeSamples
I've got a test scene, with a single game object which has an audio source, and the following behaviour:
public class AudioTest : MonoBehaviour
{
private int m_LastSample;
// Use this for initialization
void Start ()
{
m_LastSample = 0;
}
// Update is called once per frame
void Update ()
{
AudioSource audio = GetComponent<AudioSource>();
float freq = (float)audio.clip.frequency;
int sample = audio.timeSamples;
int sampleDelta = sample - m_LastSample;
if (sampleDelta < 0)
sampleDelta += audio.clip.samples;
float delta = (float)sampleDelta / freq;
print (string.Format("Freq={0} Curr={1} Last={2} Delta={3} Time.deltaTime={4}", freq, sample, m_LastSample, delta, Time.deltaTime));
m_LastSample = sample;
}
}
The output I get from this is:
Freq=44100 Curr=43008 Last=41984 Delta=0.02321995 Time.deltaTime=0.01595402
Freq=44100 Curr=43008 Last=43008 Delta=0 Time.deltaTime=0.01716399
Freq=44100 Curr=44032 Last=43008 Delta=0.02321995 Time.deltaTime=0.01597601
Freq=44100 Curr=45056 Last=44032 Delta=0.02321995 Time.deltaTime=0.01675498
which is to me unexpected because
a) the sample position doesn't appear to be updated every frame and b) the time delta that I calculate is somewhat larger than Time.deltaTime
Can I not use AudioSource.timeSamples in this way?
The behaviour I'm after is to eg. spawn something at point A sync'd with audio, and then have the object move to point B sync'd to another beat. The audio I'm using for the test is a short, looped sample that only contains 4 beats, hence the test for wraparound.
Answer by ecc83 · Jan 02, 2013 at 11:08 PM
Right after a bit more digging I found more info here
http://forum.unity3d.com/threads/147834-A-list-of-audio-bugs-(iOS-mostly)
Which confirmed that timeSamples gives the PCM offset of the current audio hardware buffer/decoding window (or whatever), not a sample accurate playback position
Your answer
Follow this Question
Related Questions
Audio start time uncertainty 2 Answers
How to make two audio tracks play in sync? 2 Answers
Synchronising Audio 1 Answer
Analyzing an audio file. 0 Answers