标签:unity
using System.Collections.Generic; using System.Linq; using UnityEngine; [RequireComponent(typeof(AudioSource))] public class MicrophoneInput : MonoBehaviour { //每秒种产生0.4M数据量 private LinkedList<float> recordData = new LinkedList<float>(); private AudioClip microphoneClip; private float voiceDetectLevel = 0.2f; private void Start() { startMicRecord(); } private void startMicRecord() { recordData.Clear(); isRecordingMic = false; microphoneClip = Microphone.Start(null, true, 600, 44100); while (!(Microphone.GetPosition(null) > 0)) { } Loom.StartSingleThread(getMicData); } private int lastReadPositio = 0; private float myMax; private bool isRecordingMic = false; private float clipPlayTime; private void getMicData() { Loom.WaitForSeconds(0.4f); //todo 加载数据并分析 int currentPosition = Microphone.GetPosition(null); int sz = currentPosition - lastReadPositio; if (sz > 1) { float[] d = new float[(sz - 1)]; microphoneClip.GetData(d, lastReadPositio); float maxValue = 0; foreach (float s in d) { maxValue = maxValue > Mathf.Abs(s) ? maxValue : Mathf.Abs(s); } myMax = maxValue; if (isRecordingMic) { if (myMax < voiceDetectLevel) { //nobody is talking. //todo maybe to relay the recored data. Loom.DispatchToMainThread(replayRecoredData); return; } foreach (float f in d) { recordData.AddLast(f); } } else { if (myMax > voiceDetectLevel) { isRecordingMic = true; recordData.Clear(); foreach (float f in d) { recordData.AddLast(f); } } } } lastReadPositio = currentPosition; // getMicData(); } public void replayRecoredData() { Microphone.End(null); float[] clipFloats = new float[recordData.Count]; int i = 0; foreach (var f in recordData) { clipFloats[i] = f; i++; } AudioClip myClip = AudioClip.Create("tom", clipFloats.Length, 1, 44100, false, false); myClip.SetData(clipFloats, 0); audio.clip = myClip; audio.Play(); audio.loop = false; audio.pitch = 1.2f; clipPlayTime = clipFloats.Length / 44100.0f; Loom.StartSingleThread(waitToRestartMic); } private void waitToRestartMic() { Loom.WaitForSeconds(clipPlayTime); startMicRecord(); } private void OnGUI() { GUI.Label(new Rect(10, 10 * 2, 100, 20), "audio" + audio); // GUI.Label(new Rect(10, 10 * 3, 100, 20), "audio" + audio.clip); // GUI.Label(new Rect(10, 10 * 4, 100, 20), "audio" + audio.clip.samples); // GUI.Label(new Rect(10, 10 * 5, 100, 20), "audio" + audio.clip.samples.ToString()); GUI.Label(new Rect(10, 10 * 6, 100, 20), "mic pos:" + Microphone.GetPosition(null)); GUI.Label(new Rect(10, 10 * 7, 100, 20), "myMax:" + myMax); GUI.Label(new Rect(10, 10 * 8, 100, 20), "recordData:" + recordData.Count()); } }完整项目地址:
标签:unity
原文地址:http://blog.csdn.net/chh19941125/article/details/46045421