赞
踩
MicroPhone
类使用这个类可以使用连接的麦克风录制到AudioClip
。
您可以从devices
属性中获取已连接麦克风的列表,然后使用Start
和End
函数使用一个可用设备启动或结束录制会话。
Microphone
类录取保存到AudioClip
中的格式为PCM格式默认16000hz、16位、单通道,这些属性在转码时很关键。不管你是自己从Unity中拖音频文件到AudioClip
中还是用Unity中Microphone
类录制音频到AudioClip
,一定要知道AudioClip
中的音频编码格式。using UnityEngine; /// <summary>收录声音</summary> public class RecordVoice { public RecordVoice() { m_samplesLength = 128; DeviceNameMIC = Microphone.devices[0];//获取设备麦克风:"Built-in Microphone" LengthSec = 60;//ASR最长60秒 Frequency = 16000; } /// <summary>录制的音频源</summary> protected AudioClip m_resultClip = null; /// <summary>是否正在计时</summary> protected bool m_isTiming = false; /// <summary>开始计时(录音)的应用时间</summary> protected float m_startTime; /// <summary>音频数据长度</summary> protected readonly int m_samplesLength; /// <summary>设备名麦克风</summary> public string DeviceNameMIC { get; set; } /// <summary>录音产生的AudioClip的长度</summary> public int LengthSec { get; set; } /// <summary>由录音产生的AudioClip的采样率</summary> public int Frequency { get; set; } #region Public /// <summary>开始</summary> public virtual void Start() { m_resultClip = Microphone.Start(DeviceNameMIC, false, LengthSec, Frequency); m_isTiming = true; m_startTime = Time.time; } /// <summary>结束</summary> public virtual void End() { Microphone.End(DeviceNameMIC); m_isTiming = false; } /// <summary>获取麦克风音量</summary> /// <returns>麦克风的音量数值</returns> public virtual float GetVolume() { float levelMax = 0; if (Microphone.IsRecording(DeviceNameMIC)) { float[] samples = new float[m_samplesLength]; int startPosition = Microphone.GetPosition(DeviceNameMIC) - (m_samplesLength + 1); if (startPosition >= 0) {//当麦克风还未正式启动时,该值会为负值,AudioClip.GetData函数会报错 m_resultClip.GetData(samples, startPosition); for (int i = 0; i < m_samplesLength; i++) { float wavePeak = samples[i]; if (levelMax < wavePeak) { levelMax = wavePeak; } } levelMax = levelMax * 99; Debug.Log("麦克风音量:" + levelMax); } } return levelMax; } /// <summary>计时</summary> public virtual void KeepTime() { if (m_isTiming) {//是否正在计时 if (Time.time - m_startTime >= LengthSec) {//时间到,结束录音 End(); Debug.Log("时间到!"); } } } #endregion }
另外,经过测试,设备名(DeviceNameMIC
)也可直接赋值为"Built-in Microphone"
,或null
。
Unity官方API(Microphone.Start)中:如果您为设备名传递一个null或空字符串,那么将使用默认麦克风。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。