麦克风(Microphone)

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 麦克风辅助类
/// </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 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;
        return Microphone.Start(deviceName, false, lengthSec, frequency);
    }

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

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号