Unity Microphone教程之 如何获取设备麦克风

2025-11-03 10:27:37

1、在Unity引擎新建一个空工程,具体如下图

Unity Microphone教程之 如何获取设备麦克风

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

Unity Microphone教程之 如何获取设备麦克风

Unity Microphone教程之 如何获取设备麦克风

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

Unity Microphone教程之 如何获取设备麦克风

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

Unity Microphone教程之 如何获取设备麦克风

Unity Microphone教程之 如何获取设备麦克风

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,挂载脚本上去,运行场景,因为电脑没有麦克风,具体如下图

Unity Microphone教程之 如何获取设备麦克风

Unity Microphone教程之 如何获取设备麦克风

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

Unity Microphone教程之 如何获取设备麦克风

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

Unity Microphone教程之 如何获取设备麦克风

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢