http://www.cocoachina.com/special/20170522/19326.html

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

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

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

TestAudio.cs 代码如下:

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
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();
                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 第二步,直接运行看结果;

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

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

MicroPhoneManager.cs  代码如下:

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
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 ();
                        }
                        return _curAudioSource;
                }
        }
  
        #region [public Way]
  
        ///         /// 获取麦克风设备
        ///         public void GetMicrophoneDevice ()
        {
                string[] mDevice = Microphone.devices;
                DeviceLength = mDevice.Length;
                if (DeviceLength == 0)
                        ShowInfoLog ("找不到麦克风设备!");
        }
  
        ///         /// 开始录音
        ///         public void StartRecordAudio ()
        {
                CurAudioSource.Stop ();
                CurAudioSource.loop = false;
                CurAudioSource.mute = true;
                CurAudioSource.clip = Microphone.Start (nulltrue, MicSecond, int.Parse (Frequency));
                while (!(Microphone.GetPosition (null) > 0)) {
                          
                }
                CurAudioSource.Play ();
                ShowInfoLog ("开始录音.....");
        }
  
        ///         /// 停止录音
        ///         public void StopRecordAudio ()
        {
                ShowInfoLog ("结束录音.....");
                if (!Microphone.IsRecording (null))
                        return;
                Microphone.End (null);
                CurAudioSource.Stop ();
                  
        }
  
        ///         /// 回放录音
        ///         public void PlayRecordAudio ()
        {
                if (Microphone.IsRecording (null))
                        return;
                if (CurAudioSource.clip == null)
                        return;
                CurAudioSource.mute = false;
                CurAudioSource.loop = false;
                CurAudioSource.Play ();
                ShowInfoLog ("播放录音.....");
        }
  
        ///         ///  打印录音信息
        ///         public void PrintRecordData ()
        {
                if (Microphone.IsRecording (null))
                  return;
                byte[] data = GetClipData ();
                string infoLog = "total length:" + data.Length + " time:" + CurAudioSource.time; 
                ShowInfoLog (infoLog); 
        }
  
        ///         /// 获取音频数据
        ///         /// The clip data.        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)
                
                        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]
  
        ///         /// 显示GUI 按钮
        ///         /// true, if GUI button was shown, false otherwise.        /// Button name.        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端运行查看结果;

Unity3D 实现录音小案例相关推荐

  1. Python:通过一个小案例深入理解IO多路复用

    通过一个小案例深入理解IO多路复用 假如我们现在有这样一个普通的需求,写一个简单的爬虫来爬取校花网的主页 import requests import timestart = time.time()u ...

  2. iptables小案例,nat表应用

    2019独角兽企业重金招聘Python工程师标准>>> iptables小案例: 需求1: 只针对filter表,预设INPUT链DROP,其他两个链ACCEPT,然后针对192.1 ...

  3. 4.10/4.11/4.12 lvm讲解 4.13 磁盘故障小案例

    4.10/4.11/4.12 lvm讲解 操作流程: 磁盘分区-->创建物理卷-->划分为卷组-->划分成逻辑卷-->格式化.挂载-->扩容. 磁盘分区 注: 创建分区时 ...

  4. python程序实例教程基础-编程小案例

    编程小案例 本小节实现一个通讯录管理程序,通过这个案例来融会贯通之前所学习的知识,该程序使用到如下知识点: 条件选择 循环 列表 字典 键盘输入 屏幕输出 编写程序 addr-manage.py 实现 ...

  5. axios vue 回调函数_Vue 02 —— Vue 入门小案例~使用 Axios 中的GET、POST请求

    作为后端攻城狮,写前端代码是一种什么体验? 相信不少人和 @Python大星 一样,有写过前端代码的经历. 记录一下,Vue 框架开发中"啼笑皆非"的故事,非专业前端人员,该案例无 ...

  6. 【Node.js学习小案例】DNS域名解析 一

    Node.js 百度百科: Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用· Node.js 借助事件驱动, 非阻塞I/ ...

  7. linux下set和eval的使用小案例精彩解答

    linux下set和eval的使用小案例解答 本博文主要是讲解学生提出的如下一行命令脚本定义的真正内涵: runlevel=$(set -- $(runlevel); eval "echo  ...

  8. shell讲解-小案例

    shell讲解-小案例 一.文件拷贝输出检查 下面测试文件拷贝是否正常,如果cp命令并没有拷贝文件myfile到myfile.bak,则打印错误信息.注意错误信息中basename $0打印脚本名.如 ...

  9. 函数作为返回值练习 作用域和作用域链及预解析 闭包 闭包小案例

    函数作为返回值练习 <!DOCTYPE html> <html lang="en"> <head><meta charset=" ...

最新文章

  1. JavaScript奇技淫巧44招(2)
  2. ***检测与防护(IDS/IPS)
  3. 在Project 2010中添加自定义任务窗格
  4. [Google Guava] 排序: Guava强大的”流畅风格比较器”
  5. Android开源框架——图表MPAndroidChart
  6. 多图 | 4人4天攻占10国榜首,只因有此神器……(文末高能预警)
  7. Flutter 构建一个完整的聊天应用程序
  8. 链表应用——多项式相加
  9. SAP Spartacus和传统的Accelerator超时机制(timeout)的区别
  10. 自己动手写CPU(8)加载存储指令的实现
  11. win7系统桌面计算机怎么打的开,windows7系统双击计算机打不开怎么解决|win7双击计算机打不开的解决方法...
  12. html音频控件隐藏,html5 – Html 5音频标签自定义控件?
  13. php 上传word文件 源码,THINKPHP中word文档的上传与下载
  14. jQueryPager(JQuery分页插件pagination实现Ajax分页)
  15. java 文件无法下载_无法从Java中的URL下载文件
  16. 成功的MES项目,前期都做了些什么?
  17. Java 网络教程: ServerSocket
  18. C# 中格式化字符串中包含 { 或者 } 如何转义?
  19. WEB SERVER调优
  20. windowskb2685811补丁_Win7/8.1 KB2685811、KB2685813和KB2670838蓝屏补丁下载汇总 (32位+64位)...

热门文章

  1. Echarts - lengend图例自定义
  2. Retrofit2深度解析
  3. SEO全攻略:中小企业新站SEO优化应该怎么做_刘小虎SEO博客
  4. HTML的iframe使用
  5. cuda8+cuDNN Faster R-CNN安装塈运行demo
  6. 戏说领域驱动设计(十二)——服务
  7. Presto学习-presto介绍
  8. CAS单点登录(十一)——单点退出
  9. Flutter 单元测试
  10. 重构之路 1---- 自动出题软件