unity汤姆猫自动检测录音,不说话自动播放
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()); } }完整项目地址:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。