In this Blog you can learn how to detect music beat and also you can learn how to do musical fun with unity gameObject.
Step 1: Create Empty GameObject and give that name Musical Bars.Inside Musical Bar GameObject Create Vertical bars like this.
Make Sure All Created Vertical bar(cube) must child Of MusicalBars gameobject
Step 2: Create AudioReactor.cs and place below code.
using UnityEngine;
using System.Collections;
public class AudioReactor : MonoBehaviour
{
private float amp;
private float[] smooth = new float[2];
public AudioClip Music1;
public Camera mainCameraObject;
public GameObject musicalBarParent;
private Transform[] musicalBars;
private Vector3[]defaultMusicalBarSize;
void Start ()
{
musicalBars = musicalBarParent.GetComponentsInChildren ();
defaultMusicalBarSize = new Vector3[musicalBars.Length];
for (int i = 0; i < musicalBars.Length; i++) {
defaultMusicalBarSize [i] = musicalBars [i].transform.localScale;
}
//Call Initialize AudioSource
InitializeAudioSource ();
}
void OnEnable (){
}
//Initialize Audio Source
void InitializeAudioSource ()
{
GetComponent ().loop = true;
GetComponent ().clip = Music1;
GetComponent ().Play ();
}
void FixedUpdate ()
{
//Call Musical Bar
SetMusicEffect (amp);
}
// Update is called once per frame
void Update ()
{
//Change the Camera Size
mainCameraObject.orthographicSize = 5f + amp / 50;
}
void SetMusicEffect (float amp)
{
//Scale Up Scale Down Musical Bar Child's Y axis
for (int i = 1; i < musicalBars.Length; i++) {
musicalBars [i].transform.localScale = new Vector3 (defaultMusicalBarSize [i].x, defaultMusicalBarSize [i].y + (amp / Random.Range (1, 5)), defaultMusicalBarSize [i].z);
}
}
void OnAudioFilterRead (float[] data, int channels)
{
for (var i = 0; i < data.Length; i = i + channels) {
// the absolute value of every sample
float absInput = Mathf.Abs (data [i]);
// smoothening filter doing its thing
smooth [0] = ((0.01f * absInput) + (0.99f * smooth [1]));
// exaggerating the amplitude
amp = smooth [0] * 7;
// it is a recursive filter, so it is doing its recursive thing
smooth [1] = smooth [0];
}
}
}
Step 3: Create Empty GameObject and give that name AudioReactor.
-Add AudioSource Component.
-Add AudioReactor.cs Script
-Imaport any audio file into your Project