unity实现录音并保存本地
本文实例为大家分享了unity实现录音并保存本地的具体代码,供大家参考,具体内容如下
我们可以使用unity自带的MicroPhone类来录音,回放录音,保存录音
具体代码如下:
usingSystem; usingSystem.Collections; usingSystem.Collections.Generic; usingSystem.IO; usingUnityEngine; publicclassMicroPhoneManager:MonoBehaviour{ publicintDeviceLength; //////录音频率 /// publicstringFrequency="44100"; publicintSamplerate=44100; //////录音时长 /// publicintMicSecond=2; stringinfoLog=""; AudioSource_curAudioSource; AudioSourceCurAudioSource { get { if(_curAudioSource==null) { _curAudioSource=gameObject.AddComponent(); } return_curAudioSource; } } #region[publicWay] /// ///获取麦克风设备 /// publicvoidGetMicrophoneDevice() { string[]mDevice=Microphone.devices; DeviceLength=mDevice.Length; if(DeviceLength==0) ShowInfoLog("找不到麦克风设备!"); } //////开始录音 /// publicvoidStartRecordAudio() { CurAudioSource.Stop(); CurAudioSource.loop=false; CurAudioSource.mute=true; CurAudioSource.clip=Microphone.Start(null,true,MicSecond,int.Parse(Frequency)); while(!(Microphone.GetPosition(null)>0)) { } CurAudioSource.Play(); ShowInfoLog("开始录音....."); } //////停止录音 /// publicvoidStopRecordAudio() { ShowInfoLog("结束录音....."); if(!Microphone.IsRecording(null)) return; Microphone.End(null); CurAudioSource.Stop(); } ///s ///回放录音 /// publicvoidPlayRecordAudio() { if(Microphone.IsRecording(null)) return; if(CurAudioSource.clip==null) return; CurAudioSource.mute=false; CurAudioSource.loop=false; CurAudioSource.Play(); ShowInfoLog("播放录音....."); } //////打印录音信息 /// publicvoidPrintRecordData() { if(Microphone.IsRecording(null)) return; byte[]data=GetClipData(); #region用户自由固定录音时长 intposition=Microphone.GetPosition(null); varsoundata=newfloat[CurAudioSource.clip.samples*CurAudioSource.clip.channels]; CurAudioSource.clip.GetData(soundata,0); varnewdata=newfloat[position*CurAudioSource.clip.channels]; for(inti=0;i///获取音频数据 /// /// Theclipdata. publicbyte[]GetClipData() { if(CurAudioSource.clip==null) { ShowInfoLog("缺少音频资源!"); returnnull; } float[]samples=newfloat[CurAudioSource.clip.samples]; CurAudioSource.clip.GetData(samples,0); byte[]outData=newbyte[samples.Length*2]; intreScaleFactor=32767; for(inti=0;i0) { GUILayout.Label("录音频率:"); Frequency=GUILayout.TextField(Frequency,GUILayout.Width(Screen.width/5),GUILayout.Height(Screen.height/20)); GUILayout.BeginVertical(); if(ShowGUIButton("开始录音")) { StartRecordAudio(); } if(ShowGUIButton("结束录音")) { StopRecordAudio(); } if(ShowGUIButton("回放录音")) { PlayRecordAudio(); } if(ShowGUIButton("获取录音数据")) { PrintRecordData(); } GUILayout.EndVertical(); } GUILayout.Label(infoLog); } #region[PrivateWay] /// ///显示GUI按钮 /// ////// true ,ifGUIbuttonwasshown,false otherwise.Buttonname. boolShowGUIButton(stringbuttonName) { returnGUILayout.Button(buttonName,GUILayout.Height(Screen.height/20),GUILayout.Width(Screen.width/5)); } voidShowInfoLog(stringinfo) { infoLog+=info; infoLog+="\r\n"; } #endregion }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。