麦克风(Microphone)

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

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 麦克风辅助类
  6. /// Microphone类录取保存到AudioClip中的格式为PCM格式,默认16000hz,16位,单通道
  7. /// </summary>
  8. public sealed class MicrophoneHelper
  9. {
  10. //获取设备名称
  11. public static string GetDeviceName()
  12. {
  13. string[] devices = Microphone.devices;
  14. if (devices == null || devices.Length == 0)
  15. {
  16. Debug.LogError("Not found microphone device.");
  17. return null;
  18. }
  19. string deviceName = devices[0];
  20. return deviceName;
  21. }
  22.  
  23. //是否有设备
  24. public static bool HasDevice()
  25. {
  26. string[] devices = Microphone.devices;
  27. return devices != null && devices.Length > 0;
  28. }
  29.  
  30. public static void StartRecord(string deviceName, bool loop, int lengthSec, int frequency)
  31. {
  32. Microphone.Start(deviceName, loop, lengthSec, frequency);
  33. }
  34.  
  35. /// <summary>
  36. /// 录制说话(类似微信的语音消息)
  37. /// 直接录音播放时有噪音
  38. /// </summary>
  39. /// <param name="lengthSec">录制时长(单位:秒)</param>
  40. public static AudioClip StartSpeech(int lengthSec=15)
  41. {
  42. string deviceName = GetDeviceName();
  43. //人说话的信号频率通常为300-3000Hz
  44. //int frequency = 3000;
  45. //麦克风的采样频率通常为 48KHz或44.1KHz
  46. int minFreq, maxFreq;
  47. Microphone.GetDeviceCaps(deviceName, out minFreq, out maxFreq);
  48. return Microphone.Start(deviceName, false, lengthSec, maxFreq);
  49. }
  50.  
  51. //停止录制
  52. public static void StopRecord()
  53. {
  54. string deviceName = GetDeviceName();
  55. if (!Microphone.IsRecording(deviceName))
  56. return;
  57. Microphone.End(deviceName);
  58. }
  59. }

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号