unity原生即支持錄音並保存爲wav文件。git
若是要保存爲mp3文件,則須要Unity3D-save-audioClip-to-MP3這個庫,其實就是lame4naudio,可是好心人給打包爲unity的package,從github上下載以後,壓縮包裏有一個audioToMP3.unitypackage,能夠在unity裏直接導入:github
Unity3D-save-audioClip-to-MP3源碼地址oop
注意,導入以後須要在File => Build Settings => Player Settings 裏設置Api Compatibility Level爲.Net 2.0,不然WaveFormat.cs會報錯:ui
The type or namespace name `InvalidDataException' could not be found.spa
注意,打包發佈的時候,另有一個坑,解決辦法能夠參考這裏:unity在editor環境下運行正常,打包發佈以後卻提示DllNotFound的解決辦法.net
代碼:code
private int Frequency = 16000; //錄音頻率 private int BitRate = 16; //比特率 private int MicSecond = 2; //每隔2秒,保存一下錄音數據 public Button bStart; public Button bStop; public Button bPlay; public Text tTip; public AudioSource au; void Start () { bStart.onClick.AddListener(OnStartClick); bStop.onClick.AddListener(OnStopClick); bPlay.onClick.AddListener(OnPlayClick); } void OnStartClick() { tTip.text += "\n開始錄音...."; au.Stop(); au.loop = false; au.mute = true; au.clip = Microphone.Start(null, true, MicSecond, Frequency); } void OnStopClick() { tTip.text += "\n中止錄音!"; if (!Microphone.IsRecording(null)) return; Microphone.End(null); au.Stop(); Mp3FromClip("d:/test.mp3", au.clip); //將錄音保存爲mp3 //WavFromClip("d:/test.wav", au.clip); //將錄音保存爲wav } void OnPlayClick() { if (Microphone.IsRecording(null)) return; if (au.clip == null) return; au.mute = false; au.loop = false; au.Play(); tTip.text += "\n播放錄音...."; } public void WavFromClip(string WavPosition, AudioClip clip) { if (Microphone.IsRecording(null)) return; Microphone.End(null); using (FileStream fs = CreateEmpty(WavPosition)) { ConvertAndWrite(fs, au.clip); WriteHeader(fs, au.clip); //wav文件頭 } } private FileStream CreateEmpty(string filepath) { FileStream fileStream = new FileStream(filepath, FileMode.Create); byte emptyByte = new byte(); for (int i = 0; i < 44; i++) //爲wav文件頭留出空間 { fileStream.WriteByte(emptyByte); } return fileStream; } private void ConvertAndWrite(FileStream fileStream, AudioClip clip) { float[] samples = new float[clip.samples]; clip.GetData(samples, 0); Int16[] intData = new Int16[samples.Length]; Byte[] bytesData = new Byte[samples.Length * 2]; int rescaleFactor = 32767; //to convert float to Int16 for (int i = 0; i < samples.Length; i++) { intData[i] = (short)(samples[i] * rescaleFactor); Byte[] byteArr = new Byte[2]; byteArr = BitConverter.GetBytes(intData[i]); byteArr.CopyTo(bytesData, i * 2); } fileStream.Write(bytesData, 0, bytesData.Length); } public void Mp3FromClip(string Mp3location, AudioClip clip) { var samples = new float[clip.samples * clip.channels]; clip.GetData(samples, 0); Int16[] intData = new Int16[samples.Length]; //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[] Byte[] bytesData = new Byte[samples.Length * 2]; //bytesData array is twice the size of //dataSource array because a float converted in Int16 is 2 bytes. float rescaleFactor = 32767; //to convert float to Int16 for (int i = 0; i < samples.Length; i++) { intData[i] = (short)(samples[i] * rescaleFactor); Byte[] byteArr = new Byte[2]; byteArr = BitConverter.GetBytes(intData[i]); byteArr.CopyTo(bytesData, i * 2); } var ms = new MemoryStream(bytesData); using (var writer = new LameMP3FileWriter(Mp3location, new WaveFormat(Frequency, BitRate, 1), LAMEPreset.ABR_16)) ms.CopyTo(writer); } private void WriteHeader(FileStream stream, AudioClip clip) { int hz = clip.frequency; int channels = clip.channels; int samples = clip.samples; stream.Seek(0, SeekOrigin.Begin); Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF"); stream.Write(riff, 0, 4); Byte[] chunkSize = BitConverter.GetBytes(stream.Length - 8); stream.Write(chunkSize, 0, 4); Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE"); stream.Write(wave, 0, 4); Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt "); stream.Write(fmt, 0, 4); Byte[] subChunk1 = BitConverter.GetBytes(16); stream.Write(subChunk1, 0, 4); UInt16 two = 2; UInt16 one = 1; Byte[] audioFormat = BitConverter.GetBytes(one); stream.Write(audioFormat, 0, 2); Byte[] numChannels = BitConverter.GetBytes(channels); stream.Write(numChannels, 0, 2); Byte[] sampleRate = BitConverter.GetBytes(hz); stream.Write(sampleRate, 0, 4); Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2 stream.Write(byteRate, 0, 4); UInt16 blockAlign = (ushort)(channels * 2); stream.Write(BitConverter.GetBytes(blockAlign), 0, 2); UInt16 bps = 16; Byte[] bitsPerSample = BitConverter.GetBytes(bps); stream.Write(bitsPerSample, 0, 2); Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data"); stream.Write(datastring, 0, 4); Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2); stream.Write(subChunk2, 0, 4); }