Unity 使用 Microphone 采集麦克风声音
1、获取麦克风,Microphone.devices
2、开始录音,Microphone.Start
3、结束录音,Microphone.End
1、MicrophoneWrapper
1 |
using System; public class MicrophoneWrapper : MonoSingleton<MicrophoneWrapper> private string TAG = "MicrophoneWrapper: "; //标记是否有麦克风 //当前录音设备名称 //录音频率,控制录音质量(8000,16000) //上次按下时间戳 //表示录音的最大时长 //实际录音长度(由于unity的录音需先指定长度,导致识别上传时候会上传多余的无效字节) //存储录音的片段 // Start is called before the first frame update } public void Init() /// <summary> StartRecording(); /// <summary> trueLength = EndRecording(); Debug.Log(TAG+ " return AudioClip data "); Debug.Log(TAG + " return AudioClip is null "); } /// <summary> if (isHaveMic == false || Microphone.IsRecording(currentDeviceName)) //开始录音 lastPressTimestamp = GetTimestampOfNowWithMillisecond(); saveAudioClip = Microphone.Start(currentDeviceName, isLoop, recordMaxLength, recordFrequency); return true; /// <summary> if (isHaveMic == false || !Microphone.IsRecording(currentDeviceName)) Debug.Log(TAG + "EndRecording Failed "); return 0; //结束录音 //向上取整,避免遗漏录音末尾 /// <summary> |
2、Test_MicrophoneWrapper
1 |
using System.Collections; [RequireComponent(typeof(AudioSource))] private AudioSource mAudioSource; // Start is called before the first frame update public void OnPointerDown(PointerEventData eventData) public void OnPointerUp(PointerEventData eventData) |
3、MonoSingleton
1 |
using UnityEngine; public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour private static readonly object locker = new object(); private static bool bAppQuitting; public static T Instance lock (locker) var singleton = new GameObject(); } protected virtual void Awake() protected virtual void OnDestroy() |