Use microphone recording to save and replay in unity

Source: Internet
Author: User

Recording class

The Microphonemanager contains start recording, stop recording, play recording, and save the recording.

 Public Partial classmicrophonemanager:monobehaviour{Private StaticMicrophonemanager m_instance; Private Static string[] Micarray =NULL;//Recording Device List    PrivateAudioClip AudioClip; PrivateDateTime BeginTime;  Public floatsensitivity= -;  Public floatloudness=0; Const intHeader_size = -; Const intRecord_time =Ten; Const intRecord_rate =44100;//Recording sampling rate//void Awake ()//{    //m_instance = this; //}     Public StaticMicrophonemanager getinstance () {if(M_instance = =NULL) {Micarray=microphone.devices; if(Micarray.length = =0) {Debug.logerror ("No mic device"); }              foreach(stringDevicestrinchmicrophone.devices) {Debug.Log ("Device name ="+devicestr); } gameobject Micmanager=NewGameobject ("Micmanager"); M_instance= micmanager.addcomponent<microphonemanager>(); }          returnm_instance; }         /// <summary>    ///Start Recording/// </summary>     Public voidStartrecord () {if(Micarray.length = =0) {Debug.Log ("No Record device!"); return; } microphone.end (NULL);//The recording is stopped before recording, the recording parameter is null when using the default recording driverBeginTime =DateTime.Now; AudioClip= Microphone.start (NULL,false, Record_time, record_rate);  while(! (Microphone.getposition (NULL) >0) ) {} Debug.Log ("Startrecord"); }        /// <summary>    ///Stop Recording/// </summary>     Public voidStoprecord () {if(Micarray.length = =0) {Debug.Log ("No Record device!"); return; }          if(! Microphone.isrecording (NULL))          {              return; } microphone.end (NULL); Debug.Log ("Stoprecord"); }    /// <summary>    ///Play Recording/// </summary>     Public voidPlayRecord () {PlayRecord (audioclip); }     Public voidPlayRecord (audioclip clip) {PlayRecord (Clip,vector3.zero); }     Public voidPlayRecord (audioclip clip, Vector3 POS) {if(Clip = =NULL) {Debug.Log ("AudioClip is null"); return;        } audiosource.playclipatpoint (clip, POS); Debug.Log ("PlayRecord"); }     Public byte[] Save () {if(AudioClip = =NULL)return NULL; returnWavutility.fromaudioclip (AudioClip); }     Public voidSave (stringPathstringfilename)    {Save (audioclip,path,filename); }     Public voidSave (audioclip clip,stringPathstringfilename) {        if(Clip = =NULL) {Debug.Log ("clip is Null,can ' t being saved"); return; } wavutility.fromaudioclip (clip, path, filename,true); }     PublicAudioClip Read (stringpath) {       returnwavutility.toaudioclip (path); }     PublicAudioClip Read (byte[] data) {       returnwavutility.toaudioclip (data); }     Publicjobject Saveaudioclip () {jobject JD=NewJobject (); jd[" Time"] = begintime.tostring ("yymmdd-hhmmss-fff"); //jd["time"] = Begintime.tofiletime (); //There is a problem with other encoding formats using Unicode encodingIdx"AudioClip"] =Encoding.Unicode.GetString (Save ()); returnJD; }}

Save the recording

Wavutility is the saving and reading of recording data, which can be saved as a local file. wav or byte array for transmission. This stuff I found on GitHub, because the code is too long to be posted, the URL put on: Https://github.com/deadlyfingers/UnityWav

Important method

-Use the "Toaudioclip" method for loading WAV file/bytes.
Loads. WAV (PCM uncompressed) files at 8,16,24 and all bits and converts data to Unity ' s audioclip.
-Use the "Fromaudioclip" method for saving WAV file/bytes.
Converts an AudioClip ' s float data to wav byte array at + bit.

public static AudioClip Toaudioclip (String filePath)

public static AudioClip Toaudioclip (byte[] filebytes, int offsetsamples = 0, String name = "wav")

public static byte[] Fromaudioclip (AudioClip audioclip)

public static byte[] Fromaudioclip (audioclip audioclip,string filepath,string filename, bool SaveAsFile = TRUE)

Playback of recordings

In order to facilitate playback, and not to introduce additional files to record the playback time and recording of the corresponding information, the recording time as a file name (ex:170515-114114-676), and at the beginning of the record an empty recording as the starting time, the playback code is as follows:

IEnumerator Playaudioclip () {string[] files =Directory.GetFiles (Savepath); if(Files. Length >0) {List<string> temp =Newlist<string>();  for(inti =0; I < files. Length; i++)            {                if(!files[i]. Contains (". Meta") temp.            ADD (Files[i]); }            string[] Audiofiles =temp.            ToArray ();            Array.Sort (audiofiles); floatInterval =0f;  for(inti =0; I < audiofiles.length-1; i++) {AudioClip clip=microphonemanager.getinstance ().                Read (Audiofiles[i]); Microphonemanager.getinstance ().                PlayRecord (clip); Interval= (float) (GetTime (Audiofiles[i +1]) -GetTime (Audiofiles[i])).                TotalSeconds;                Debug.Log (interval); yield return Newwaitforseconds (interval); } microphonemanager.getinstance (). PlayRecord (Microphonemanager.getinstance (). Read (Audiofiles[audiofiles.length-1])            ); }         }

Use microphone recording to save and replay in unity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.