Unity Microphone教程之 如何获取设备麦克风
1、在Unity引擎新建一个空工程,具体如下图

2、在场景中,添加一个 Button 和一个 Text,布局设置如下图


3、在工程中,新建一个脚本 OpenMicrophone,双击打开脚本进行编写,具体如下图

4、OpenMicrophone 脚本的代码和代码说明具体如下图


5、OpenMicrophone 脚本具体内容如下:
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(AudioSource))]
public class OpenMicrophone : MonoBehaviour {
private AudioSource aud;
private Button btn;
private Text txt;
private bool isHaveMicrophone = false;
// Use this for initialization
void Start () {
aud = this.GetComponent<AudioSource>();
btn = GameObject.Find("Button").GetComponent<Button>();
txt = GameObject.Find("Text").GetComponent<Text>();
btn.onClick.AddListener(OnClickBtn);
//获取麦克风设备,判断蛇摆是否有麦克风
string[] devices = Microphone.devices;
if (devices.Length > 0)
{
isHaveMicrophone = true;
txt.text = "设备有麦克风:"+ devices[0];
}
else {
isHaveMicrophone = false;
txt.text = "设备没有麦克风";
}
}
private void OnClickBtn() {
if (isHaveMicrophone == false) {
return;
}
//有麦克风就打开使用麦克风
/*
* public static AudioClip Start(string deviceName, bool loop, int lengthSec, int frequency);
* deviceName The name of the device.
* loop Indicates whether the recording should continue recording if lengthSec is reached,
and wrap around and record from the beginning of the AudioClip.
* lengthSec Is the length of the AudioClip produced by the recording.
* frequency The sample rate of the AudioClip produced by the recording.
*/
aud.clip = Microphone.Start( null, true, 10, 44100);
aud.Play();
}
}
6、脚本编译正确,回到Unity,在场景中新建一个 GameObject,挂载脚本上去,运行场景,因为电脑没有麦克风,具体如下图


7、File - Build Settings,切换平台,打包编译,具体如下图

8、在安卓上有麦克风,运行结果如下图
