使用Unity 3D实现录音方式 VR开发教程

我们都知道,在Unity中有提供麦克风MicroPhone相关的API,今天小编和大家一起来看一下如何实现录制场景中的声音,并且可以在应用中使用。

 

     1.首先,一起回顾一下快速在游戏中创建音频剪辑,官方文档:https://docs.unity3d.com/ScriptReference/AudioClip.Create.html

 

       1.0 第一步,新建项目并且在场景附加一个TestAudio.cs 组件类;

 

          TestAudio.cs 代码如下:

 

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestAudio : MonoBehaviour {
        public string Frequency="440";
        public int Samplerate = 44100;
        public int Position = 0;
        void OnGUI()
        {
                if (GUI.Button (new Rect (10, 10, 100, 100), "创建音频剪辑"))
                        CreateAudioSource ();
                GUI.Label (new Rect (10, 200, 100, 100),"Position:"+Position.ToString());
        }
        
        void CreateAudioSource()
        {
                AudioClip myClip = AudioClip.Create("MyFirstSound", Samplerate * 2, 1, Samplerate, true, OnAudioRead, OnAudioSetPosition);
                AudioSource aud = GetComponent<AudioSource>();
                aud.clip = myClip;
                aud.Play();
        }
        void OnAudioRead(float[] data)
        {
                int count = 0;
                while (count < data.Length)
                {
                        data[count] = Mathf.Sign(Mathf.Sin(2 * Mathf.PI * int.Parse(Frequency) * Position / Samplerate));
                        Position++;
                        count++;
                }
        }
        void OnAudioSetPosition(int newPosition)
        {
                Position = newPosition;
        }
}
       1.1 第二步,直接运行看结果;

 

          使用Unity 3D实现录音方式 VR开发教程

 

     2. 然后,一起学习如何在Unity中调用MicroPhone相关的接口,官方文档:https://docs.unity3d.com/ScriptReference/30_search.html?q=Microphone.IsRecording

 

       2.0 第一步,新建项目并且在场景中附加一个MicroPhoneManager.cs 组件类;

 

         MicroPhoneManager.cs  代码如下:

 

?
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MicroPhoneManager : MonoBehaviour {
        public int DeviceLength;
        public string Frequency="440";
        public int Samplerate = 44100;
        public int MicSecond=2;
        string infoLog="";
        AudioSource _curAudioSource;
        AudioSource CurAudioSource
        {
                get{
                        if (_curAudioSource == null) {
                                _curAudioSource = gameObject.AddComponent<AudioSource> ();
                        }
                        return _curAudioSource;
                }
        }
        #region [public Way]
        /// <summary>
        /// 获取麦克风设备
        /// </summary>
        public void GetMicrophoneDevice ()
        {
                string[] mDevice = Microphone.devices;
                DeviceLength = mDevice.Length;
                if (DeviceLength == 0)
                        ShowInfoLog ("找不到麦克风设备!");
        }
        /// <summary>
        /// 开始录音
        /// </summary>
        public void StartRecordAudio ()
        {
                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 ("开始录音.....");
        }
        /// <summary>
        /// 停止录音
        /// </summary>
        public void StopRecordAudio ()
        {
                ShowInfoLog ("结束录音.....");
                if (!Microphone.IsRecording (null))
                        return;
                Microphone.End (null);
                CurAudioSource.Stop ();
                
        }
        /// <summary>
        /// 回放录音
        /// </summary>
        public void PlayRecordAudio ()
        {
                if (Microphone.IsRecording (null))
                        return;
                if (CurAudioSource.clip == null)
                        return;
                CurAudioSource.mute = false;
                CurAudioSource.loop = false;
                CurAudioSource.Play ();
                ShowInfoLog ("播放录音.....");
        }
        /// <summary>
        ///  打印录音信息
        /// </summary>
        public void PrintRecordData ()
        {
                if (Microphone.IsRecording (null))
                  return;
                byte[] data = GetClipData ();
                string infoLog = "total length:" + data.Length + " time:" + CurAudioSource.time; 
                ShowInfoLog (infoLog); 
        }
        /// <summary>
        /// 获取音频数据
        /// </summary>
        /// <returns>The clip data.</returns>
        public  byte[] GetClipData ()
        {
                if (CurAudioSource.clip == null) {
                        ShowInfoLog ("缺少音频资源!");
                        return null;
                }
                float[] samples = new float[CurAudioSource.clip.samples];
                CurAudioSource.clip.GetData (samples, 0);
                byte[] outData = new byte[samples.Length * 2];
                int reScaleFactor = 32767;
                for (int i = 0; i < samples.Length; i++) {
                        short tempShort = (short)(samples [i] * reScaleFactor);
                        byte[] tempData = System.BitConverter.GetBytes (tempShort);
                        outData [i * 2] = tempData [0];
                        outData [i * 2 + 1] = tempData [1];
                }
                if (outData == null || outData.Length <= 0) {
                
                        ShowInfoLog ("获取音频数据失败!");
                        return null;
                }
                return outData;
        }
        #endregion
        void OnGUI()
        {
                if (DeviceLength == 0) {
                        if (ShowGUIButton("获取麦克风设备")) 
                        
                                GetMicrophoneDevice ();
                        }
                }
                else if(DeviceLength>0)
                
                        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 [Private Way]
        /// <summary>
        /// 显示GUI 按钮
        /// </summary>
        /// <returns><c>true</c>, if GUI button was shown, <c>false</c> otherwise.</returns>
        /// <param name="buttonName">Button name.</param>
        bool ShowGUIButton (string buttonName)
        {
                return  GUILayout.Button (buttonName, GUILayout.Height (Screen.height / 20), GUILayout.Width (Screen.width / 5));
        }
        void ShowInfoLog (string info)
        {
                infoLog += info;
                infoLog += "/r/n";
        }
        #endregion
}

 

       2.1 第二步,我们可以部署到android/iphone真机上运行,当然也可以直接在PC端运行查看结果;

 

            使用Unity 3D实现录音方式 VR开发教程

 

            使用Unity 3D实现录音方式 VR开发教程