- Home /
Get Audio TimeLine
Hello!
I am trying to get the audio timeline of a music playing on a game.
In Editor, when i select the audio, it shows on the inspector the timeline. There are anyway to get this as an image for example, with code?
IT should be something like : AudioSource.timeSamples / AudioSource.clip.samples
Then to implement an UI looking like the inspector there are bit more lines of code involved.
Thanks, but that is not what i want.
I just discover the answer. I posted below.
Answer by LuisCRSousa · Feb 18, 2016 at 06:06 PM
I did it.
Sharing my raw code. A function that receives an audioclip and return a sprite with the timeline.
I apply also an low pass filter to better results.
One sample returned image:
public static Sprite getMusicTimeline(AudioClip audioClip)
{
float[] dataClip;
Texture2D texture;
int[] dataFinal;
dataClip = new float[audioClip.samples];
audioClip.GetData(dataClip, 0);
texture = new Texture2D(500, 400, TextureFormat.ARGB32, false);
dataFinal = new int[texture.width];
for (int x = 0; x < texture.width; x++)
{
int indexData = (int)Functions.mapTruncate(x, 0, texture.width, 0, dataClip.Length - 1);
int valueOnImage = (int)(Functions.mapTruncate(dataClip[indexData], 0, 1f, 0, texture.height / 2 - 1));
dataFinal[x] = valueOnImage;
}
for (int i = 4; i < dataFinal.Length - 4; ++i)
dataFinal[i] = (dataFinal[i - 4] + dataFinal[i - 3] + dataFinal[i - 2] + dataFinal[i - 1] + dataFinal[i] + dataFinal[i + 1] + dataFinal[i + 2] + dataFinal[i + 3] + +dataFinal[i + 4]) / 5;
for (int x = 0; x < texture.width; x++)
{
for (int y = texture.height / 2 - 1; y < dataFinal[x] + texture.height / 2 - 1; y++)
texture.SetPixel(x, y, Color.white);
for (int y = dataFinal[x] + texture.height / 2 - 1; y < texture.height; y++)
texture.SetPixel(x, y, Color.clear);
for (int y = texture.height / 2 - 1; y > texture.height / 2 - 1 - dataFinal[x]; y--)
texture.SetPixel(x, y, Color.white);
for (int y = texture.height / 2 - 1 - dataFinal[x]; y >= 0; y--)
texture.SetPixel(x, y, Color.clear);
}
texture.Apply();
Rect rec = new Rect(0, 0, texture.width, texture.height);
return Sprite.Create(texture, rec, new Vector2(0.5f, 0.5f), 100);
}
At a guess, it remaps values from one arbitrary range to another, while clamping the values. Something like:
public static class Functions {
public static float mapTruncate (this float value, float from1, float to1, float from2, float to2) {
return $$anonymous$$athf.Clamp((value - from1) / (to1 - from1) * (to2 - from2) + from2, from2, to2);
}
}
Your answer
Follow this Question
Related Questions
Animate Audio Source Pitch/Speed in Timeline 0 Answers
Control game elements with Timeline 0 Answers
Timeline and Audiosource not synced? 0 Answers