Unity 基础 之 Microphone 麦克风的简单方便调用的封装

Unity 基础  之  Microphone 麦克风的简单方便调用的封装

 

目录

Unity 基础  之  Microphone 麦克风的简单方便调用的封装

一、简单介绍

二、实现原理

三、注意事项

四、实现步骤

六、关键代码


 

一、简单介绍

Unity中的一些基础知识点。

本节介绍,在Unity中调用 麦克风,进行了录音说话,并且播放出来的功能封装,仅供参考。

 

二、实现原理

1、获取麦克风,Microphone.devices

2、开始录音,Microphone.Start

3、结束录音,Microphone.End

 

三、注意事项

1、本文默认开启 0 号 Microphone 麦克风,进行录音测试

2、设置了默认录音时长为 10 秒,可以根据需要做修改

 

四、实现步骤

1、打开Unity,新建一个空工程

Unity 基础 之 Microphone 麦克风的简单方便调用的封装_第1张图片

 

2、在工程中,添加脚本,封装 Microphone 和测试 Microphone 封装的类

Unity 基础 之 Microphone 麦克风的简单方便调用的封装_第2张图片

 

3、在场景中,添加一个按钮测试录音

Unity 基础 之 Microphone 麦克风的简单方便调用的封装_第3张图片

 

4、把测试脚本,挂载到 Button 上

Unity 基础 之 Microphone 麦克风的简单方便调用的封装_第4张图片

 

5、运行场景(或者打包),测试即可

 

六、关键代码

1、MicrophoneWrapper

using System;
using UnityEngine;

public class MicrophoneWrapper : MonoSingleton
{

    private string TAG = "MicrophoneWrapper: ";

    //标记是否有麦克风
    private bool isHaveMic = false;

    //当前录音设备名称
    string currentDeviceName = string.Empty;

    //录音频率,控制录音质量(8000,16000)
    int recordFrequency = 8000;

    //上次按下时间戳
    double lastPressTimestamp = 0;

    //表示录音的最大时长
    int recordMaxLength = 10;

    //实际录音长度(由于unity的录音需先指定长度,导致识别上传时候会上传多余的无效字节)
    //通过该字段,获取有效录音长度,上传时候剪切到无效的字节数据即可
    int trueLength = 0;

    //存储录音的片段
    [HideInInspector]
    public AudioClip saveAudioClip;


    // Start is called before the first frame update
    void Start()
    {

    }


    public void Init()
    {
        //获取麦克风设备,判断是否有麦克风设备
        if (Microphone.devices.Length > 0)
        {
            isHaveMic = true;
            currentDeviceName = Microphone.devices[0];
        }
        else {
            Debug.Log(TAG + " Microphone.devices is null(0) ");
        }
    }



    /// 
    /// 按下录音按钮
    /// 
    /// 
    public void OnStartRecord()
    {

        StartRecording();
    }

    /// 
    /// 放开录音按钮
    /// 
    /// 
    public AudioClip OnStopRecord()
    {

        trueLength = EndRecording();
        if (trueLength > 1)
        {

            Debug.Log(TAG+ " return AudioClip data ");
            return saveAudioClip;
            
        }

        Debug.Log(TAG + " return AudioClip is null ");
        return null;

    }


    /// 
    /// 开始录音
    /// 
    /// 
    /// 
    /// 
    /// 
    private bool StartRecording(bool isLoop = false) //8000,16000
    {
        Debug.Log(TAG+"StartRecording   ");

        if (isHaveMic == false || Microphone.IsRecording(currentDeviceName))
        {
            return false;
        }

        //开始录音
        /*
         * public static AudioClip Start(string deviceName, bool loop, int lengthSec, int frequency);
         * deviceName   录音设备名称.
         * loop         如果达到长度,是否继续记录
         * lengthSec    指定录音的长度.
         * frequency    音频采样率   
         */

        lastPressTimestamp = GetTimestampOfNowWithMillisecond();

        saveAudioClip = Microphone.Start(currentDeviceName, isLoop, recordMaxLength, recordFrequency);

        return true;
    }

    /// 
    /// 录音结束,返回实际的录音时长
    /// 
    /// 
    private int EndRecording()
    {
        Debug.Log(TAG+"EndRecording   ");

        if (isHaveMic == false || !Microphone.IsRecording(currentDeviceName))
        {

            Debug.Log(TAG + "EndRecording  Failed ");

            return 0;
        }

        //结束录音
        Microphone.End(currentDeviceName);

        //向上取整,避免遗漏录音末尾
        return Mathf.CeilToInt((float)(GetTimestampOfNowWithMillisecond() - lastPressTimestamp) / 1000f);
    }

    /// 
    /// 获取毫秒级别的时间戳,用于计算按下录音时长
    /// 
    /// 
    private double GetTimestampOfNowWithMillisecond()
    {
        return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
    }
}

 

 

2、Test_MicrophoneWrapper

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(AudioSource))]
public class Test_MicrophoneWrapper : MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{

    private AudioSource mAudioSource;
    private AudioClip mAudioClip;

    // Start is called before the first frame update
    void Start()
    {
        MicrophoneWrapper.Instance.Init();
        mAudioSource = GetComponent();
    }


    public void OnPointerDown(PointerEventData eventData)
    {
        this.transform.GetChild(0).GetComponent().text = "松开播放";
        MicrophoneWrapper.Instance.OnStartRecord();
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        this.transform.GetChild(0).GetComponent().text = "按下说话录音";
        mAudioClip = MicrophoneWrapper.Instance.OnStopRecord();
        if (mAudioSource != null && mAudioClip != null)
        {
            mAudioSource.PlayOneShot(mAudioClip);
        }
        else {
            Debug.Log(" mAudioSource or mAudioClip is null ");
        }
    }
}

 

 

3、MonoSingleton

using UnityEngine;

public abstract class MonoSingleton : MonoBehaviour where T : MonoBehaviour
{
    private static T instance = null;

    private static readonly object locker = new object();

    private static bool bAppQuitting;

    public static T Instance
    {
        get
        {
            if (bAppQuitting)
            {
                instance = null;
                return instance;
            }

            lock (locker)
            {
                if (instance == null)
                {
                    // 保证场景中只有一个 单例
                    T[] managers = Object.FindObjectsOfType(typeof(T)) as T[];
                    if (managers.Length != 0)
                    {
                        if (managers.Length == 1)
                        {
                            instance = managers[0];
                            instance.gameObject.name = typeof(T).Name;
                            return instance;
                        }
                        else
                        {
                            Debug.LogError("Class " + typeof(T).Name + " exists multiple times in violation of singleton pattern. Destroying all copies");
                            foreach (T manager in managers)
                            {
                                Destroy(manager.gameObject);
                            }
                        }
                    }


                    var singleton = new GameObject();
                    instance = singleton.AddComponent();
                    singleton.name = "(singleton)" + typeof(T);
                    singleton.hideFlags = HideFlags.None;
                    DontDestroyOnLoad(singleton);

                }
                instance.hideFlags = HideFlags.None;
                return instance;
            }
        }
    }

    protected virtual void Awake()
    {
        bAppQuitting = false;
    }

    protected virtual void OnDestroy()
    {
        bAppQuitting = true;
    }
}

 

 

你可能感兴趣的:(基础,Unity)