Unity Tom Cat automatically detects recordings, does not speak auto-play
Script
Using system.collections.generic;using system.linq;using unityengine; [Requirecomponent (typeof (Audiosource))]public class microphoneinput:monobehaviour{//per second produces 0.4M data volume private Linkedli st<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 loads the data and parses 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) {//nob Ody 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 (Ten, 2, +), "audio" + audio); // Gui. Label (New Rect (Ten, 3, +), "audio" + Audio.clip); Gui. Label (New Rect (Ten, 4, +), "audio" + audio.clip.samples); Gui. Label (New Rect (Ten, 5, +), "audio" + audio.clip.samples.ToString ()); Gui. Label (New Rect (Ten, 6, +), "Mic pos:" + microphone.getposition (null)); Gui. Label (New Rect (Ten, 7, +), "Mymax:" + Mymax); Gui. Label (New Rect (Ten, 8, +), "RecordData:" + recorddata.count ()); }}
full Project Address:http://download.csdn.net/detail/chh19941125/8744043
Unity Tom Cat automatically detects recordings, does not speak auto-play