AudioRecorder.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. using NAudio.CoreAudioApi;
  2. using NAudio.Wave;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace AudioRecorder
  11. {
  12. public class AudioRecorder
  13. {
  14. private const string _fileExtension = ".wav";
  15. /// <summary>
  16. /// 录音(wav格式)
  17. /// </summary>
  18. private static WaveInEvent _recorder;
  19. /// <summary>
  20. /// 文件名
  21. /// </summary>
  22. private static string _fileName;
  23. /// <summary>
  24. /// 流写入文件
  25. /// </summary>
  26. private static WaveFileWriter _writer;
  27. /// <summary>
  28. /// 信号量,用于解决关闭录音时线程占用文件
  29. /// </summary>
  30. private static ManualResetEvent _manualResetEvent;
  31. private static AudioRecorder _instance;
  32. public static AudioRecorder Instance
  33. {
  34. get
  35. {
  36. if (_instance == null)
  37. {
  38. _instance = new AudioRecorder();
  39. }
  40. return _instance;
  41. }
  42. }
  43. /// <summary>
  44. /// 开启录音
  45. /// </summary>
  46. public void Start(string localAudioCachePath)
  47. {
  48. try
  49. {
  50. _recorder = new WaveInEvent();
  51. _recorder.DeviceNumber = 0;
  52. _recorder.WaveFormat = new WaveFormat(16000, 16, 1);
  53. _fileName = Guid.NewGuid().ToString() + _fileExtension;
  54. if (!Directory.Exists(localAudioCachePath))
  55. {
  56. Directory.CreateDirectory(localAudioCachePath);
  57. }
  58. _writer = new WaveFileWriter(Path.Combine(localAudioCachePath, _fileName), _recorder.WaveFormat);
  59. // 当有音频数据时写入器将其写入流
  60. _recorder.DataAvailable += (s, e) =>
  61. {
  62. _writer.Write(e.Buffer, 0, e.BytesRecorded);
  63. };
  64. // 当录音停止时关闭写入器
  65. _recorder.RecordingStopped += (s, e) =>
  66. {
  67. _writer.Close();
  68. _manualResetEvent.Set();
  69. };
  70. _recorder.StartRecording();
  71. }
  72. catch (Exception ex)
  73. {
  74. throw ex;
  75. }
  76. }
  77. /// <summary>
  78. /// 结束录音
  79. /// </summary>
  80. public string Stop(string localAudioCachePath)
  81. {
  82. try
  83. {
  84. _manualResetEvent = new ManualResetEvent(false);
  85. _recorder.StopRecording();
  86. _manualResetEvent.WaitOne(2000);
  87. var filePath = Path.Combine(localAudioCachePath, _fileName);
  88. if (!File.Exists(filePath))
  89. {
  90. return string.Empty;
  91. }
  92. // 将录音数据转为base64
  93. var buffer = File.ReadAllBytes(filePath);
  94. var base64 = Convert.ToBase64String(buffer);
  95. return base64;
  96. }
  97. catch (Exception ex)
  98. {
  99. throw ex;
  100. }
  101. return string.Empty;
  102. }
  103. public float GetAudioDeviceVolume(AudioDeviceTypeEnum audioTypeEnum, Action<string> logger)
  104. {
  105. try
  106. {
  107. var audioEnumerator = new MMDeviceEnumerator();
  108. if (audioTypeEnum == AudioDeviceTypeEnum.Mic)
  109. {
  110. var microphone = audioEnumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications);
  111. if (microphone != null)
  112. {
  113. return microphone.AudioEndpointVolume.MasterVolumeLevelScalar;
  114. }
  115. }
  116. else
  117. {
  118. var speaker = audioEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
  119. if (speaker != null)
  120. {
  121. return speaker.AudioEndpointVolume.MasterVolumeLevelScalar;
  122. }
  123. }
  124. return 0;
  125. }
  126. catch (Exception ex)
  127. {
  128. logger("Get device default volume ex:" + ex.ToString());
  129. return 0;
  130. }
  131. }
  132. public List<string> GetAudioDevices(AudioDeviceTypeEnum audioTypeEnum)
  133. {
  134. var audioEnumerator = new MMDeviceEnumerator();
  135. var devices = audioEnumerator.EnumerateAudioEndPoints(audioTypeEnum == AudioDeviceTypeEnum.Speaker ?
  136. DataFlow.Render : DataFlow.Capture, DeviceState.Active);
  137. if (devices == null)
  138. {
  139. return new List<string>();
  140. }
  141. return devices.Select(x => x.FriendlyName).ToList();
  142. }
  143. public bool SetSystemAudioDevice(string deviceName)
  144. {
  145. var audioEnumerator = new MMDeviceEnumerator();
  146. var devices = audioEnumerator.EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active);
  147. var selectedDevice = devices.FirstOrDefault(device => device.FriendlyName == deviceName);
  148. if (selectedDevice != null)
  149. {
  150. // AudioDeviceManager.SetDefaultAudioDevice(deviceName, true);
  151. return true;
  152. }
  153. else
  154. {
  155. return false;
  156. }
  157. }
  158. /// <summary>
  159. /// 调整声音设备音量
  160. /// </summary>
  161. /// <param name="audioTypeEnum"></param>
  162. /// <param name="volume"></param>
  163. /// <param name="logger"></param>
  164. public void AdjustAudioDevice(AudioDeviceTypeEnum audioTypeEnum, double volume, Action<string> logger)
  165. {
  166. var audioEnumerator = new MMDeviceEnumerator();
  167. var microphone = audioEnumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications);
  168. var speaker = audioEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
  169. if (volume < 0 || volume > 1)
  170. {
  171. logger($"Invalid volum {volume}");
  172. return;
  173. }
  174. // 设置音量大小 (0.0f 到 1.0f)
  175. float micVolume = (float)volume; // 50% 音量
  176. float speakerVolume = (float)volume; // 75% 音量
  177. if (audioTypeEnum == AudioDeviceTypeEnum.Mic)
  178. {
  179. // 设置麦克风音量
  180. if (microphone.AudioEndpointVolume != null)
  181. {
  182. microphone.AudioEndpointVolume.MasterVolumeLevelScalar = micVolume;
  183. }
  184. }
  185. if (audioTypeEnum == AudioDeviceTypeEnum.Speaker)
  186. {
  187. // 设置扬声器音量
  188. if (speaker.AudioEndpointVolume != null)
  189. {
  190. speaker.AudioEndpointVolume.MasterVolumeLevelScalar = speakerVolume;
  191. }
  192. }
  193. }
  194. }
  195. public enum AudioDeviceTypeEnum
  196. {
  197. /// <summary>
  198. /// 麦克风
  199. /// </summary>
  200. Mic,
  201. /// <summary>
  202. /// 扬声器
  203. /// </summary>
  204. Speaker,
  205. }
  206. }