麦克风(Microphone)

作者:追风剑情 发布于:2022-2-8 12:04 分类:Unity3d

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 麦克风辅助类
/// Microphone类录取保存到AudioClip中的格式为PCM格式,默认16000hz,16位,单通道
/// </summary>
public sealed class MicrophoneHelper
{
    //获取设备名称
    public static string GetDeviceName()
    {
        string[] devices = Microphone.devices;
        if (devices == null || devices.Length == 0)
        {
            Debug.LogError("Not found microphone device.");
            return null;
        }
        string deviceName = devices[0];
        return deviceName;
    }

    //是否有设备
    public static bool HasDevice()
    {
        string[] devices = Microphone.devices;
        return devices != null && devices.Length > 0;
    }

    public static void StartRecord(string deviceName, bool loop, int lengthSec, int frequency)
    {
        Microphone.Start(deviceName, loop, lengthSec, frequency);
    }

    /// <summary>
    /// 录制说话(类似微信的语音消息)
    /// 直接录音播放时有噪音
    /// </summary>
    /// <param name="lengthSec">录制时长(单位:秒)</param>
    public static AudioClip StartSpeech(int lengthSec=15)
    {
        string deviceName = GetDeviceName();
        //人说话的信号频率通常为300-3000Hz
        //int frequency = 3000;
        //麦克风的采样频率通常为 48KHz或44.1KHz
        int minFreq, maxFreq;
        Microphone.GetDeviceCaps(deviceName, out minFreq, out maxFreq);
        return Microphone.Start(deviceName, false, lengthSec, maxFreq);
    }

    //停止录制
    public static void StopRecord()
    {
        string deviceName = GetDeviceName();
        if (!Microphone.IsRecording(deviceName))
            return;
        Microphone.End(deviceName);
    }
}

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号