Unity获取麦克风音量(实现音效波浪效果)
1.每个方块(Cube)为一个波浪添加脚本MusicDance
2.整体获取马克风音量大小脚本MusicManager
MusicDance
public class MusicDance : MonoBehaviour{ private float targetPosY; private float speed; [HideInInspector]public bool isDance; void Start() { RandomTargetPosY(); } void Update() { if (isDance) { if (Mathf.Abs(transform.localScale.y - targetPosY) >= 1f) { transform.localScale = new Vector3(1, Mathf.SmoothDamp(transform.localScale.y, targetPosY, ref speed, Random.Range(0.2f,1f)), 1); } else { RandomTargetPosY(); } } else { //没有声音时,从当前高度下落到正常高度 if (Mathf.Abs(transform.localScale.y - targetPosY) >= 0.1f) { transform.localScale = new Vector3(1, Mathf.SmoothDamp(transform.localScale.y, 1f, ref speed, Random.Range(0.2f, 1f)), 1); } } } void RandomTargetPosY() { targetPosY = UnityEngine.Random.Range(1f, 12f); }}
MusicManager
public class MusicManager : MonoBehaviour{ [SerializeField]private MusicDance[] musicDances; private AudioClip audioClip; private string strs; private void Awake() { audioClip = Microphone.Start(strs, true, 999, 44100); strs = Microphone.devices[0]; } void Start() { } private void Update() { for (int i = 0; i < musicDances.Length; i++) { musicDances[i].isDance = DanceOrNot(); } } bool DanceOrNot() { float[] datas = new float[128]; int startPos = Microphone.GetPosition(strs) - 127; if (startPos < 0) return false; audioClip.GetData(datas, startPos); float max = -1f; for (int i = 0; i < datas.Length; i++) { if (max < datas[i]) { max = datas[i]; } } max *= 1000; if (max > 20) { return true; } else { return false; } }}
赞 (0)