服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - unity实现录音并保存本地

unity实现录音并保存本地

2022-09-02 11:40贪玩的孩纸时代 C#

这篇文章主要为大家详细介绍了unity实现录音并保存本地,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了unity实现录音并保存本地的具体代码,供大家参考,具体内容如下

我们可以使用unity自带的MicroPhone类来录音,回放录音,保存录音

具体代码如下:

?
1
2
3
4
5
6
7
8
9
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
 
public class MicroPhoneManager : MonoBehaviour {
 
  public int DeviceLength;
  /// <summary>
  /// 录音频率
  /// </summary>
  public string Frequency = "44100";
  public int Samplerate = 44100;
  /// <summary>
  /// 录音时长
  /// </summary>
  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>s
  /// 回放录音
  /// </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();
    #region 用户自由固定录音时长
    int position = Microphone.GetPosition(null);
    var soundata = new float[CurAudioSource.clip.samples * CurAudioSource.clip.channels];
    CurAudioSource.clip.GetData(soundata, 0);
 
    var newdata = new float[position * CurAudioSource.clip.channels];
    for (int i = 0; i < newdata.Length; i++) {
      newdata[i] = soundata[i];
    }
    CurAudioSource.clip = AudioClip.Create(CurAudioSource.clip.name, position, CurAudioSource.clip.channels, CurAudioSource.clip.frequency, false);
    CurAudioSource.clip.SetData(newdata, 0);
 
    Microphone.End(null);
    #endregion
    using (FileStream fs = CreateEmpty(Application.persistentDataPath + "/dd.wav")) {
      ConvertAndWrite(fs, CurAudioSource.clip);
      WriteHeader(fs, CurAudioSource.clip);
    }
 
    string infoLog = "total length:" + data.Length + " time:" + CurAudioSource.time;
    ShowInfoLog(infoLog);
  }
  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);
 
  }
  private FileStream CreateEmpty(string filepath)
  {
    FileStream fileStream = new FileStream(filepath, FileMode.Create);
    byte emptyByte = new byte();
 
    for (int i = 0; i < 44; i++) //preparing the header
    {
      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);
  }
  /// <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
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/yiwei151/article/details/77897742

延伸 · 阅读

精彩推荐
  • C#webBrowser执行js的方法,并返回值,c#后台取值的实现

    webBrowser执行js的方法,并返回值,c#后台取值的实现

    下面小编就为大家带来一篇webBrowser执行js的方法,并返回值,c#后台取值的实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过...

    C#教程网11112021-12-13
  • C#C#实现简单计算器功能

    C#实现简单计算器功能

    给大家分享用C#写出一个计算机功能的全部代码分享,有兴趣的朋友可以跟着做一下。...

    彬菌8052022-02-22
  • C#C#实现将浮点数表示的货币数量以汉字大写形式输出的方法

    C#实现将浮点数表示的货币数量以汉字大写形式输出的方法

    这篇文章主要介绍了C#实现将浮点数表示的货币数量以汉字大写形式输出的方法,涉及C#针对浮点数的遍历与字符替换操作技巧,具有一定参考借鉴价值,需要的...

    北风其凉3852021-10-11
  • C#C#处理猜拳问题的简单实例(非窗体)

    C#处理猜拳问题的简单实例(非窗体)

    下面小编就为大家带来一篇C#处理猜拳问题的简单实例(非窗体)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网9672021-12-01
  • C#C#计算矩阵的逆矩阵方法实例分析

    C#计算矩阵的逆矩阵方法实例分析

    这篇文章主要介绍了C#计算矩阵的逆矩阵方法,较为详细的分析了逆矩阵的计算原理与相关的C#实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    北风其凉10532021-10-11
  • C#C#获取进程或线程相关信息的方法

    C#获取进程或线程相关信息的方法

    这篇文章主要介绍了C#获取进程或线程相关信息的方法,涉及C#操作进程及线程的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    我心依旧7492021-10-21
  • C#C# 监控 Windows 文件夹的方法

    C# 监控 Windows 文件夹的方法

    这篇文章主要介绍了C# 监控 Windows 文件夹的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    Programer Cat10832022-08-30
  • C#C#操作INI文件的辅助类IniHelper

    C#操作INI文件的辅助类IniHelper

    这篇文章主要为大家详细介绍了C#操作INI文件的辅助类IniHelper,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    马洪彪8832022-02-21