- Home /
GameObject reacts to audio source
I was wondering if there was a way to link a GameObject to an audio source to make it react with it? Like you can do in AfterEffects.
Currently, I just want the GameObject to move up and down in time with the beat of the music so nothing too ambitious. Anyone know if this can be done or how to go about it?
Answer by TimXT · Sep 29, 2013 at 12:29 PM
Wow, cool question!
Hmmm, there is one way which is using AudioClip.GetData(); This gives you access to the samples of an audio clip which I think you can use to check what the actual volume level of the audio source is (not the overall volume, but the actual level at that instant).
You can try doing this:
On the game object of the audio source attach this script:
float[] samples;
void Start()
{
//make an array to contain all the samples of the clip currently playing
samples = new float[audio.clip.samples*audio.clip.channels];
//store all the sample data of the clip in this array.
audio.clip.GetData(samples, 0);
}
void Update()
{
//in every frame get the current sample of the clip from the samples array.
float currentSample = samples[audio.timeSamples];
/*then do whatever you want with it,
e.g. you can use it to set the Y position
of a gameobject so that it moves up and down
according to the beat. */
}
You can also check the current sample level at longer intervals using coroutines instead of on update, to avoid the game object from jerking too much on little volume changes.
A downside of this though is that the audio clip you are playing cannot be compressed or streaming which will increase the size of the sound file.
Anyways, hope this helps!
I used this code, and it's really close. Assigning the samples wasn't accounting for multiple channels. Line 16 needs to look like: float currentSample = samples[audio.timeSamples*audio.clip.channels]; That will get the first channel of each sample.
You could add this to the frequency. Often the snare has a high frequency when the bass drum has a low frequency. This way you could make the object move in accordance to the frequency of the wave.