星火直播PC
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FFMpeg.cs 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. using AForge.Video.DirectShow;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using VisioForge.Shared.NAudio.CoreAudioApi;
  10. using VisioForge.Shared.NAudio.Wave;
  11. namespace Common.system
  12. {
  13. /// <summary>
  14. /// ffmpeg帮助类
  15. /// 创建人:赵耀
  16. /// 创建时间::2020年8月22日
  17. /// 需要安装\SSCR\Setup Screen Capturer Recorder v0.12.10.exe
  18. /// 本地调试需要配置环境变量 将ffmpeg.exe位置配置到环境变量的path中
  19. /// </summary>
  20. public class FFMpeg
  21. {
  22. public Process myProcess = null;
  23. /// <summary>
  24. /// 是否输出录课录屏日志
  25. /// </summary>
  26. public bool OutputVideoLog = FileToolsCommon.GetConfigValue("OutputVideoLog") != "0";
  27. /// <summary>
  28. /// ffmpeg输出日志文件地址 每个文件2MB左右
  29. /// </summary>
  30. private string LogPath = "";
  31. /// <summary>
  32. /// 是否可以录制扬声器
  33. /// </summary>
  34. private bool IsRecordSpeaker = true;
  35. /// <summary>
  36. /// 是否可以录制麦克风
  37. /// </summary>
  38. private bool IsRecordMicrophone = true;
  39. /// <summary>
  40. /// 录制屏幕
  41. /// </summary>
  42. /// <param name="FilePath">文件存储路径</param>
  43. public bool StartRecordingVideo(string FilePath, Size size, out string ErrMessage)
  44. {
  45. while (myProcess != null)
  46. {
  47. Thread.Sleep(100);
  48. }
  49. ErrMessage = null;
  50. //路径
  51. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  52. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  53. //文件保存路径
  54. string PathName = GetRSFilePathName(FilePath);
  55. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  56. foreach (Process KillProcess in KillProcessArray)
  57. {
  58. KillProcess.Kill();
  59. }
  60. myProcess = new Process();
  61. LogPath = CreateffmpegLog();
  62. string MicrophoneName = null;
  63. #region 检测麦克风扬声器
  64. string AudioPath = FileToolsCommon.GetFileAbsolutePath("/temp/audio/");
  65. FileToolsCommon.CreateDirectory(AudioPath);
  66. string audioSpeakerPath = AudioPath + "adoS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";//FileToolsCommon.GetFileAbsolutePath("adoS.m");
  67. string audioMicrophonePath = AudioPath + "adoM" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";//FileToolsCommon.GetFileAbsolutePath("adoM.m");
  68. try
  69. {
  70. FileToolsCommon.DeleteFile(audioSpeakerPath);
  71. FileToolsCommon.DeleteFile(audioMicrophonePath);
  72. }
  73. catch (Exception)
  74. {
  75. }
  76. if (StartRecordSpeakerAudio(audioSpeakerPath))
  77. {
  78. IsRecordSpeaker = true;
  79. }
  80. else
  81. {
  82. //无法录制扬声器音频
  83. IsRecordSpeaker = false;
  84. }
  85. StopRecordAudio(2);
  86. Thread.Sleep(100);
  87. if (StartRecordAudio(audioMicrophonePath))
  88. {
  89. IsRecordMicrophone = true;
  90. }
  91. else
  92. {
  93. //无法录制麦克风
  94. IsRecordMicrophone = false;
  95. }
  96. StopRecordAudio(1);
  97. #endregion
  98. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  99. string SpeakerStr = "";
  100. string MicrophoneStr = "";
  101. if (IsRecordSpeaker)
  102. {
  103. SpeakerStr = "-f dshow -i audio=\"virtual-audio-capturer\" ";
  104. }
  105. if (IsRecordMicrophone)
  106. {
  107. MicrophoneName = GetMicrophoneName();
  108. if (!string.IsNullOrWhiteSpace(MicrophoneName))
  109. {
  110. MicrophoneStr = "-f dshow -i audio=\"" + MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 ";
  111. }
  112. }
  113. switch (Extension.ToUpper())
  114. {
  115. case ".MP4":
  116. myProcess.StartInfo.Arguments = SpeakerStr + MicrophoneStr + " -f gdigrab -framerate 6 -offset_x 0 -offset_y 0 -video_size " + size.Width + "x" + size.Height + " -i desktop -pix_fmt yuv420p -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac " + PathName;
  117. //myProcess.StartInfo.Arguments = SpeakerStr + MicrophoneStr + " -f dshow -i video=\"screen-capture-recorder\" -pix_fmt yuv420p -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac " + PathName;
  118. //if (string.IsNullOrWhiteSpace(MicrophoneName))
  119. //{
  120. // myProcess.StartInfo.Arguments = "-f dshow -i video=\"screen-capture-recorder\" -f dshow -i audio=\"virtual-audio-capturer\" -vcodec libx264 -acodec libmp3lame -r 15 -crf 22 " + PathName; //ffmpeg的参数
  121. //}
  122. //else
  123. //{
  124. // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  125. // MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 -f dshow -i video=\"screen-capture-recorder\" -pix_fmt yuv420p -vcodec h264 -preset:v ultrafast -tune:v zerolatency -acodec aac -ar 44100 -ac 2 " + PathName; //ffmpeg的参数
  126. //}
  127. break;
  128. case ".AVI":
  129. case ".FLV":
  130. myProcess.StartInfo.Arguments = SpeakerStr + MicrophoneStr + " -f gdigrab -framerate 6 -offset_x 0 -offset_y 0 -video_size " + size.Width + "x" + size.Height + " -i desktop -pix_fmt yuv420p -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac -f " + Extension.ToLower().Replace(".", "") + " " + PathName;
  131. //if (string.IsNullOrWhiteSpace(MicrophoneName))
  132. //{
  133. // myProcess.StartInfo.Arguments = "-f dshow -i video=\"screen-capture-recorder\" -f dshow -i audio=\"virtual-audio-capturer\" -vcodec libx264 -acodec libmp3lame -r 15 -crf 22 -f " + Extension.ToLower() + " " + PathName; //ffmpeg的参数
  134. //}
  135. //else
  136. //{
  137. // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  138. // MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 -f dshow -i video=\"screen-capture-recorder\" -pix_fmt yuv420p -vcodec h264 -preset:v ultrafast -tune:v zerolatency -acodec aac -ar 44100 -ac 2 -f " + Extension.ToLower() + " " + PathName; //ffmpeg的参数
  139. //}
  140. break;
  141. default:
  142. myProcess.StartInfo.Arguments = SpeakerStr + MicrophoneStr + " -f gdigrab -framerate 6 -offset_x 0 -offset_y 0 -video_size " + size.Width + "x" + size.Height + " -i desktop -pix_fmt yuv420p -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac " + PathName;
  143. break;
  144. }
  145. if (OutputVideoLog)
  146. {
  147. LogHelper.WriteInfoLog("【录屏】:" + myProcess.StartInfo.Arguments);
  148. }
  149. FileToolsCommon.AppendText(LogPath, "【录屏】:" + myProcess.StartInfo.Arguments + "\r\n");
  150. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  151. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  152. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  153. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  154. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  155. try
  156. {
  157. myProcess.Start();
  158. myProcess.BeginErrorReadLine();
  159. }
  160. catch (Exception ex)
  161. {
  162. if (ex.Message.Contains("访问"))
  163. {
  164. ErrMessage = "访问被拒绝,请关闭杀毒软件或新任此软件后重试!";
  165. }
  166. else
  167. {
  168. ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
  169. }
  170. LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
  171. myProcess.Dispose();
  172. myProcess = null;
  173. return false;
  174. }
  175. return true;
  176. }
  177. /// <summary>
  178. /// 录制音频
  179. /// </summary>
  180. /// <param name="Mp3Path">MP3音频位置</param>
  181. public bool StartRecordingAudio(string Mp3Path, out string ErrMessage)
  182. {
  183. ErrMessage = null;
  184. while (myProcess != null)
  185. {
  186. Thread.Sleep(100);
  187. }
  188. //路径
  189. string Path = FileToolsCommon.GetDirectoryName(Mp3Path);
  190. //文件保存路径
  191. string PathName = GetFilePathName(Mp3Path);
  192. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  193. foreach (Process KillProcess in KillProcessArray)
  194. {
  195. KillProcess.Kill();
  196. }
  197. string MicrophoneName = null;
  198. #region 检测麦克风扬声器
  199. string AudioPath = FileToolsCommon.GetFileAbsolutePath("/temp/audio/");
  200. FileToolsCommon.CreateDirectory(AudioPath);
  201. string audioSpeakerPath = AudioPath + "adoS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";
  202. string audioMicrophonePath = AudioPath + "adoM" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";
  203. try
  204. {
  205. FileToolsCommon.DeleteFile(audioSpeakerPath);
  206. FileToolsCommon.DeleteFile(audioMicrophonePath);
  207. }
  208. catch (Exception)
  209. {
  210. }
  211. if (StartRecordSpeakerAudio(audioSpeakerPath))
  212. {
  213. IsRecordSpeaker = true;
  214. }
  215. else
  216. {
  217. //无法录制扬声器音频
  218. IsRecordSpeaker = false;
  219. }
  220. StopRecordAudio(2);
  221. Thread.Sleep(100);
  222. if (StartRecordAudio(audioMicrophonePath))
  223. {
  224. IsRecordMicrophone = true;
  225. MicrophoneName = GetMicrophoneName();
  226. }
  227. else
  228. {
  229. //无法录制麦克风
  230. IsRecordMicrophone = false;
  231. }
  232. StopRecordAudio(1);
  233. if (!IsRecordSpeaker && !IsRecordMicrophone)
  234. {
  235. ErrMessage = "无法录制声音,请关闭杀毒软件,确保声卡和麦克风处于可用状态!";
  236. return false;
  237. }
  238. #endregion
  239. myProcess = new Process();
  240. LogPath = CreateffmpegLog();
  241. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  242. if (IsRecordSpeaker && IsRecordMicrophone)
  243. {
  244. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  245. MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
  246. }
  247. else if (IsRecordSpeaker)
  248. {
  249. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" " + PathName;
  250. }
  251. else if (IsRecordMicrophone)
  252. {
  253. //录制麦克风
  254. if (!string.IsNullOrWhiteSpace(MicrophoneName))
  255. {
  256. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"" +
  257. MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
  258. }
  259. }
  260. if (OutputVideoLog)
  261. {
  262. LogHelper.WriteInfoLog("【录音】:" + myProcess.StartInfo.Arguments);
  263. }
  264. FileToolsCommon.AppendText(LogPath, "【录音】:" + myProcess.StartInfo.Arguments + "\r\n");
  265. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  266. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  267. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  268. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  269. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  270. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  271. try
  272. {
  273. myProcess.Start(); //启动线程
  274. myProcess.BeginErrorReadLine(); //开始异步读取
  275. }
  276. catch (Exception ex)
  277. {
  278. if (ex.Message.Contains("访问"))
  279. {
  280. ErrMessage = "无法录制声音,访问被拒绝,请关闭杀毒软件或信任此软件后重试!";
  281. }
  282. else
  283. {
  284. ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
  285. }
  286. LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
  287. myProcess.Dispose();
  288. myProcess = null;
  289. return false;
  290. }
  291. return true;
  292. }
  293. /// <summary>
  294. /// 暂停录制
  295. /// </summary>
  296. public bool SuspendFFmpeg()
  297. {
  298. if (myProcess != null)
  299. {
  300. myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
  301. myProcess.Close();//关闭进程
  302. myProcess.Dispose();//释放资源
  303. }
  304. #region 进程是否已经释放
  305. bool IsRunning = true;
  306. while (IsRunning)
  307. {
  308. IsRunning = false;
  309. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  310. foreach (Process KillProcess in ProcessArray)
  311. {
  312. IsRunning = true;
  313. Thread.Sleep(100);
  314. }
  315. }
  316. #endregion
  317. myProcess = null;
  318. return true;
  319. //myProcess.Kill();
  320. }
  321. /// <summary>
  322. /// 停止录制并合成文件
  323. /// </summary>
  324. /// <param name="FilePath">文件存储路径 必须与开始时的路径完全一致</param>
  325. public bool StopFFmpeg(string FilePath)
  326. {
  327. //文件完整路径
  328. if (myProcess != null)
  329. {
  330. myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
  331. myProcess.Close();//关闭进程
  332. myProcess.Dispose();//释放资源
  333. }
  334. #region 进程是否已经释放
  335. bool IsRunning = true;
  336. while (IsRunning)
  337. {
  338. IsRunning = false;
  339. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  340. foreach (Process KillProcess in ProcessArray)
  341. {
  342. IsRunning = true;
  343. Thread.Sleep(100);
  344. }
  345. }
  346. #endregion
  347. myProcess = null;
  348. Thread t1 = new Thread(MergeVideoOrAudio);
  349. t1.Start(FilePath);
  350. return true;
  351. //文件合成
  352. }
  353. /// <summary>
  354. /// 图片音频合成视频
  355. /// </summary>
  356. /// <param name="ImageListPath">图片列表位置 命名为1.png 2.png</param>
  357. /// <param name="Mp3Path">MP3音频位置</param>
  358. /// <param name="VideoSavePath">视频保存位置</param>
  359. /// <param name="Frequency">每秒帧率</param>
  360. /// <param name="VideoWidth">视频宽度</param>
  361. /// <param name="VideoHeight">视频高度</param>
  362. public bool SynthesisVideo(string ImageListPath, string Mp3Path, string VideoSavePath, int Frequency, int VideoWidth, int VideoHeight, out string ErrMessage)
  363. {
  364. //new Thread(new ThreadStart(new Action(() =>
  365. //{
  366. //}))).Start();
  367. while (myProcess != null)
  368. {
  369. Thread.Sleep(100);
  370. }
  371. ErrMessage = null;
  372. string Extension = FileToolsCommon.GetIOExtension(VideoSavePath);//扩展名
  373. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  374. //Debug.WriteLine(KillProcessArray.Length.ToString());
  375. foreach (Process KillProcess in KillProcessArray)
  376. {
  377. KillProcess.Kill();
  378. }
  379. myProcess = new Process();
  380. try
  381. {
  382. LogPath = CreateffmpegLog();
  383. string mp3Str = "";
  384. #region 判断音频是否存在
  385. if (!string.IsNullOrWhiteSpace(Mp3Path))
  386. {
  387. if (FileToolsCommon.IsExistFile(Mp3Path))
  388. {
  389. mp3Str = "-i " + Mp3Path;
  390. }
  391. }
  392. #endregion
  393. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  394. switch (Extension.ToUpper())
  395. {
  396. case ".MP4":
  397. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  398. ImageListPath + @"%d.png " +
  399. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  400. VideoSavePath;
  401. break;
  402. case ".AVI":
  403. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  404. ImageListPath + @"%d.png " +
  405. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f AVI " +
  406. VideoSavePath;
  407. break;
  408. case ".FLV":
  409. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  410. ImageListPath + @"%d.png " +
  411. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f FLV " +
  412. VideoSavePath;
  413. break;
  414. default:
  415. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  416. ImageListPath + @"%d.png " +
  417. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  418. VideoSavePath;
  419. break;
  420. }
  421. if (OutputVideoLog)
  422. {
  423. LogHelper.WriteInfoLog("【图片音频合成视频】:" + myProcess.StartInfo.Arguments);
  424. }
  425. FileToolsCommon.AppendText(LogPath, "【图片音频合成视频】:" + myProcess.StartInfo.Arguments + "\r\n");
  426. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  427. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  428. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  429. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  430. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  431. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  432. try
  433. {
  434. myProcess.Start(); //启动线程
  435. myProcess.BeginErrorReadLine(); //开始异步读取
  436. myProcess.WaitForExit(); //阻塞等待进程结束
  437. myProcess.Close(); //关闭进程
  438. }
  439. catch (Exception ex)
  440. {
  441. if (ex.Message.Contains("访问"))
  442. {
  443. ErrMessage = "访问被拒绝,请关闭杀毒软件或新任此软件后重试!";
  444. }
  445. else
  446. {
  447. ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
  448. }
  449. LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
  450. myProcess.Dispose();
  451. myProcess = null;
  452. return false;
  453. }
  454. myProcess.Dispose(); //释放资源
  455. #region 进程是否已经释放
  456. bool IsRunning = true;
  457. while (IsRunning)
  458. {
  459. IsRunning = false;
  460. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  461. foreach (Process KillProcess in ProcessArray)
  462. {
  463. IsRunning = true;
  464. Thread.Sleep(100);
  465. }
  466. }
  467. #endregion
  468. myProcess = null;
  469. //生成视频后删除图片和音频保存列表
  470. //FileToolsCommon.DeleteDirectory(ImageListPath);
  471. //FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(Mp3Path));
  472. Thread.Sleep(100);
  473. FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(VideoSavePath) + "temp");
  474. return true;
  475. }
  476. catch (Exception ex)
  477. {
  478. LogHelper.WriteErrLog("【视频合成】(SynthesisVideo)视频生成失败," + ex.Message, ex);
  479. ErrMessage = ex.Message;
  480. return false;
  481. }
  482. //Dispatcher.Invoke(() =>
  483. //{
  484. //});
  485. //// 允许不同线程间的调用
  486. //Control.CheckForIllegalCrossThreadCalls = false;
  487. }
  488. /// <summary>
  489. /// 视频音频合成
  490. /// </summary>
  491. /// <param name="FilePath">存储路径</param>
  492. public void MergeVideoOrAudio(object FilePathobj)
  493. {
  494. //new Thread(new ThreadStart(new Action(() =>
  495. //{
  496. //Dispatcher.Invoke(() =>
  497. //{
  498. //});
  499. //}))).Start();
  500. while (myProcess != null)
  501. {
  502. Thread.Sleep(100);
  503. }
  504. //路径
  505. string FilePath = (string)FilePathobj;
  506. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  507. //扩展名
  508. string Extension = FileToolsCommon.GetIOExtension(FilePath);
  509. //Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  510. //foreach (var KillProcess in KillProcessArray)
  511. //{
  512. // KillProcess.Kill();
  513. //}
  514. #region 判断文件是否存在
  515. if (Extension.ToUpper() == ".MP3")
  516. {
  517. if (!FileToolsCommon.IsExistFile(Path + "temp/filelist.d"))
  518. {
  519. return;
  520. }
  521. }
  522. else
  523. {
  524. if (!FileToolsCommon.IsExistFile(Path + "temprs/filelist.d"))
  525. {
  526. return;
  527. }
  528. }
  529. #endregion
  530. myProcess = new Process();
  531. LogPath = CreateffmpegLog();
  532. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  533. if (Extension.ToUpper() == ".MP3")
  534. {
  535. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temp/filelist.d -c copy " + FilePath;
  536. }
  537. else
  538. {
  539. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temprs/filelist.d -c copy " + FilePath;
  540. }
  541. if (OutputVideoLog)
  542. {
  543. LogHelper.WriteInfoLog("【音视频合成】:" + myProcess.StartInfo.Arguments);
  544. }
  545. FileToolsCommon.AppendText(LogPath, "【音视频合成】:" + myProcess.StartInfo.Arguments + "\r\n");
  546. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  547. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  548. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  549. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  550. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  551. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  552. myProcess.Start(); //启动线程
  553. myProcess.BeginErrorReadLine(); //开始异步读取
  554. myProcess.WaitForExit(); //阻塞等待进程结束
  555. myProcess.Close(); //关闭进程
  556. myProcess.Dispose(); //释放资源
  557. #region 进程是否已经释放
  558. bool IsRunning = true;
  559. while (IsRunning)
  560. {
  561. IsRunning = false;
  562. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  563. foreach (Process KillProcess in ProcessArray)
  564. {
  565. IsRunning = true;
  566. Thread.Sleep(100);
  567. }
  568. }
  569. #endregion
  570. myProcess = null;
  571. if (Extension.ToUpper() == ".MP3")
  572. {
  573. FileToolsCommon.DeleteDirectory(Path + "temp/");
  574. }
  575. else
  576. {
  577. FileToolsCommon.DeleteDirectory(Path + "temprs/");
  578. }
  579. }
  580. /// <summary>
  581. /// 获取文件完整路径 音频
  582. /// </summary>
  583. /// <param name="FilePath">文件路径</param>
  584. /// <returns></returns>
  585. private string GetFilePathName(string FilePath)
  586. {
  587. //路径
  588. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  589. //Path.GetFileName(FilePath);//获取文件名
  590. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  591. string tempFilePath = Path + "temp/";
  592. //创建临时目录
  593. FileToolsCommon.CreateDirectory(tempFilePath);
  594. //创建记录文件
  595. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  596. {
  597. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  598. }
  599. int num = 1;
  600. string CompleteFilePath = tempFilePath + num + Extension;
  601. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  602. {
  603. num++;
  604. CompleteFilePath = tempFilePath + num + Extension;
  605. }
  606. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  607. return CompleteFilePath;
  608. }
  609. /// <summary>
  610. /// 获取文件完整路径 录屏
  611. /// </summary>
  612. /// <param name="FilePath">文件路径</param>
  613. /// <returns></returns>
  614. private string GetRSFilePathName(string FilePath)
  615. {
  616. //路径
  617. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  618. //Path.GetFileName(FilePath);//获取文件名
  619. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  620. string tempFilePath = Path + "temprs/";
  621. //创建临时目录
  622. FileToolsCommon.CreateDirectory(tempFilePath);
  623. //创建记录文件
  624. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  625. {
  626. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  627. }
  628. int num = 1;
  629. string CompleteFilePath = tempFilePath + num + Extension;
  630. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  631. {
  632. num++;
  633. CompleteFilePath = tempFilePath + num + Extension;
  634. }
  635. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  636. return CompleteFilePath;
  637. }
  638. /// <summary>
  639. /// 生成缩略图
  640. /// </summary>
  641. /// <param name="VideoPath">视频地址</param>
  642. /// <param name="ImagePath">图片地址</param>
  643. /// <param name="Width">图片大小</param>
  644. /// <param name="Height">图片大小</param>
  645. public bool GenerateThumbnails(string VideoPath, string ImagePath, int Width = 0, int Height = 0)
  646. {
  647. while (myProcess != null)
  648. {
  649. Thread.Sleep(100);
  650. }
  651. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  652. foreach (Process KillProcess in KillProcessArray)
  653. {
  654. KillProcess.Kill();
  655. }
  656. string WHStr = "";
  657. if (Width > 0)
  658. {
  659. WHStr = " -s " + Width + "x" + Height;
  660. }
  661. try
  662. {
  663. myProcess = new Process();
  664. LogPath = CreateffmpegLog();
  665. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  666. //myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s " + thubWidth + "*" + thubHeight + " -f image2 \"" + ImagePath + "\"";
  667. myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2" + WHStr + " -f image2 \"" + ImagePath + "\"";
  668. if (OutputVideoLog)
  669. {
  670. LogHelper.WriteInfoLog("【生成缩略图】:" + myProcess.StartInfo.Arguments);
  671. }
  672. FileToolsCommon.AppendText(LogPath, "【生成缩略图】:" + myProcess.StartInfo.Arguments + "\r\n");
  673. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  674. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  675. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  676. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  677. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  678. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  679. myProcess.Start(); //启动线程
  680. myProcess.BeginErrorReadLine(); //开始异步读取
  681. myProcess.WaitForExit(); //阻塞等待进程结束
  682. myProcess.Close(); //关闭进程
  683. myProcess.Dispose(); //释放资源
  684. #region 进程是否已经释放
  685. bool IsRunning = true;
  686. while (IsRunning)
  687. {
  688. IsRunning = false;
  689. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  690. foreach (Process KillProcess in ProcessArray)
  691. {
  692. IsRunning = true;
  693. Thread.Sleep(100);
  694. }
  695. }
  696. #endregion
  697. myProcess = null;
  698. return true;
  699. }
  700. catch (Exception ex)
  701. {
  702. LogHelper.WriteErrLog("【生成缩略图】(GenerateThumbnails)缩略图生成失败," + ex.Message, ex);
  703. return false;
  704. }
  705. }
  706. /// <summary>
  707. /// 视频转码
  708. /// </summary>
  709. /// <param name="VideoPathName">源视频</param>
  710. /// <param name="VideoSavePathName">目标视频存储路径</param>
  711. /// <param name="Width">宽</param>
  712. /// <param name="Height">高</param>
  713. /// <returns></returns>
  714. public bool VideoTranscode(string VideoPathName, string VideoSavePathName, int Width, int Height)
  715. {
  716. while (myProcess != null)
  717. {
  718. Thread.Sleep(100);
  719. }
  720. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  721. foreach (Process KillProcess in KillProcessArray)
  722. {
  723. KillProcess.Kill();
  724. }
  725. try
  726. {
  727. myProcess = new Process();
  728. LogPath = CreateffmpegLog();
  729. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  730. myProcess.StartInfo.Arguments = "-i " + VideoPathName + " -acodec copy -vcodec libx264 -s " + Width + "*" + Height + " " + VideoSavePathName;
  731. if (OutputVideoLog)
  732. {
  733. LogHelper.WriteInfoLog("【视频转码】:" + myProcess.StartInfo.Arguments);
  734. }
  735. FileToolsCommon.AppendText(LogPath, "【视频转码】:" + myProcess.StartInfo.Arguments + "\r\n");
  736. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  737. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  738. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  739. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  740. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  741. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  742. myProcess.Start(); //启动线程
  743. myProcess.BeginErrorReadLine(); //开始异步读取
  744. myProcess.WaitForExit(); //阻塞等待进程结束
  745. myProcess.Close(); //关闭进程
  746. myProcess.Dispose(); //释放资源
  747. #region 进程是否已经释放
  748. bool IsRunning = true;
  749. while (IsRunning)
  750. {
  751. IsRunning = false;
  752. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  753. foreach (Process KillProcess in ProcessArray)
  754. {
  755. IsRunning = true;
  756. Thread.Sleep(100);
  757. }
  758. }
  759. #endregion
  760. myProcess = null;
  761. Thread.Sleep(200);
  762. FileToolsCommon.DeleteFile(VideoPathName);
  763. return true;
  764. }
  765. catch (Exception ex)
  766. {
  767. LogHelper.WriteErrLog("【视频转码】(VideoTranscode)视频转码失败," + ex.Message, ex);
  768. return false;
  769. }
  770. }
  771. /// <summary>
  772. /// 创建日志文件
  773. /// </summary>
  774. /// <returns></returns>
  775. private string CreateffmpegLog()
  776. {
  777. string LogFileName = DateTime.Now.ToString("yyyyMMdd");
  778. string LogFilePath = FileToolsCommon.GetFileAbsolutePath("/Log/FFMpegLog/");
  779. FileToolsCommon.CreateDirectory(LogFilePath);
  780. string LogName = LogFilePath + LogFileName + ".log";
  781. try
  782. {
  783. if (!FileToolsCommon.IsExistFile(LogName))
  784. {
  785. FileToolsCommon.CreateFile(LogName);
  786. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  787. "****************************************************************************************************\r\n");
  788. return LogName;
  789. }
  790. else
  791. {
  792. int num = 0;
  793. while (FileToolsCommon.GetFileSizeByMB(LogName) > 2)
  794. {
  795. num++;
  796. LogName = LogFilePath + LogFileName + "_" + num + ".log";
  797. FileToolsCommon.CreateFile(LogName);
  798. }
  799. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  800. "****************************************************************************************************\r\n");
  801. return LogName;
  802. }
  803. }
  804. catch (Exception)
  805. {
  806. return LogName;
  807. }
  808. }
  809. /// <summary>
  810. /// 输出结果
  811. /// </summary>
  812. /// <param name="sendProcess"></param>
  813. /// <param name="output"></param>
  814. private void Output(object sendProcess, DataReceivedEventArgs output)
  815. {
  816. if (!string.IsNullOrEmpty(output.Data))
  817. {
  818. FileToolsCommon.AppendText(LogPath, "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "】:");
  819. FileToolsCommon.AppendText(LogPath, output.Data + "\r\n");
  820. }
  821. }
  822. #region 麦克风声卡检测
  823. #region 获取麦克风
  824. private bool IsMicrophone = false;
  825. /// <summary>
  826. /// 使用FFmpeg获取的麦克风名
  827. /// </summary>
  828. private string MicrophoneNameInfo = "";
  829. /// <summary>
  830. /// 获取麦克风名称
  831. /// </summary>
  832. /// <returns></returns>
  833. public string GetMicrophoneName()
  834. {
  835. return GetAudioInDevices();
  836. //string FullName = GetInDeviceFull();
  837. //if(string.IsNullOrWhiteSpace(MicrophoneNameInfo))
  838. //{
  839. // return FullName;
  840. //}
  841. ////byte[] bufferASCII = Encoding.Default.GetBytes(MicrophoneNameInfo);
  842. ////string str = Encoding.UTF8.GetString(bufferASCII);
  843. ////str = str.Replace("?", " ");
  844. ////int num = str.Length;
  845. ////int num1 = FullName.Length;
  846. //if (FullName.Contains("(") || FullName.Contains("("))
  847. //{
  848. // string EName = FullName.Substring(FullName.IndexOf("(")+1);
  849. // if(string.IsNullOrEmpty(EName))
  850. // {
  851. // EName = FullName.Substring(FullName.IndexOf("(") + 1);
  852. // EName = EName.Substring(0, EName.LastIndexOf(")"));
  853. // }
  854. // else
  855. // {
  856. // //EName = EName.Substring(0, EName.LastIndexOf(")"));
  857. // }
  858. // if(MicrophoneNameInfo.Contains(EName))
  859. // {
  860. // return FullName;
  861. // }
  862. // else
  863. // {
  864. // return GetInDeviceName();
  865. // }
  866. //}
  867. //else
  868. //{
  869. // return FullName;
  870. //}
  871. }
  872. /// <summary>
  873. /// 使用FFmpeg获取设备名称--待定
  874. /// </summary>
  875. public void GetMToFFmpeg()
  876. {
  877. //return;
  878. new Thread(new ThreadStart(new Action(() =>
  879. {
  880. try
  881. {
  882. while (myProcess != null)
  883. {
  884. Thread.Sleep(100);
  885. }
  886. myProcess = new Process();
  887. LogPath = CreateffmpegLog();
  888. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  889. myProcess.StartInfo.Arguments = " -list_devices true -f dshow -i dummy";
  890. if (OutputVideoLog)
  891. {
  892. LogHelper.WriteInfoLog("【获取设备信息】:" + myProcess.StartInfo.Arguments);
  893. }
  894. FileToolsCommon.AppendText(LogPath, "【获取设备信息】:" + myProcess.StartInfo.Arguments + "\r\n");
  895. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  896. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  897. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  898. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  899. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  900. myProcess.ErrorDataReceived += GetDevInfoData;
  901. myProcess.Start(); //启动线程
  902. myProcess.BeginErrorReadLine(); //开始异步读取
  903. myProcess.WaitForExit(); //阻塞等待进程结束
  904. myProcess.Close(); //关闭进程
  905. myProcess.Dispose(); //释放资源
  906. myProcess = null;
  907. }
  908. catch (Exception ex)
  909. {
  910. LogHelper.WriteErrLog("【获取设备信息】(GetMToFFmpeg)信息获取失败:" + ex.Message, ex);
  911. }
  912. }))).Start();
  913. }
  914. /// <summary>
  915. /// 使用FFmpeg获取设备名称--待定
  916. /// </summary>
  917. /// <param name="sender"></param>
  918. /// <param name="e"></param>
  919. private void GetDevInfoData(object sender, DataReceivedEventArgs e)
  920. {
  921. if (!string.IsNullOrEmpty(e.Data))
  922. {
  923. if (IsMicrophone)
  924. {
  925. try
  926. {
  927. MicrophoneNameInfo = e.Data;
  928. MicrophoneNameInfo = MicrophoneNameInfo.Substring(MicrophoneNameInfo.IndexOf("]") + 1);
  929. MicrophoneNameInfo = MicrophoneNameInfo.Replace("\"", "");
  930. MicrophoneNameInfo = MicrophoneNameInfo.Trim();
  931. #region 测试
  932. //byte[] bufferASCII = Encoding.Default.GetBytes(MicrophoneNameInfo);
  933. //MicrophoneNameInfo = Encoding.UTF8.GetString(bufferASCII); // 统一使用UTF-8
  934. ////System.Text.Encoding GB2312 = System.Text.Encoding.GetEncoding("GB2312");
  935. ////byte[] gb = GB2312.GetBytes(MicrophoneNameInfo);
  936. ////MicrophoneNameInfo = Encoding.UTF8.GetString(gb);
  937. #endregion
  938. IsMicrophone = false;
  939. FileToolsCommon.AppendText(LogPath, e.Data);
  940. //FileToolsCommon.AppendText(LogPath, "\r\n***************************************************\r\n");
  941. }
  942. catch (Exception ex)
  943. {
  944. LogHelper.WriteErrLog("【获取设备信息】(GetDevInfoData)信息获取失败:" + ex.Message, ex);
  945. }
  946. }
  947. else
  948. {
  949. if (e.Data.Contains("DirectShow audio devices"))
  950. {
  951. //FileToolsCommon.AppendText(LogPath, "\r\n***************************************************\r\n");
  952. IsMicrophone = true;
  953. }
  954. FileToolsCommon.AppendText(LogPath, e.Data);
  955. FileToolsCommon.AppendText(LogPath, "\r\n");
  956. }
  957. }
  958. }
  959. /// <summary>
  960. /// AForge获取麦克风
  961. /// </summary>
  962. /// <returns></returns>
  963. public static string GetAudioInDevices()
  964. {
  965. List<string> devicesList = new List<string>();
  966. try
  967. {
  968. FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.AudioInputDevice);
  969. foreach (FilterInfo device in videoDevices)
  970. {
  971. devicesList.Add(device.Name);
  972. }
  973. }
  974. catch (ApplicationException)
  975. {
  976. //Console.WriteLine("No local capture devices");
  977. }
  978. if (devicesList.Count > 1)
  979. {
  980. return devicesList[1];
  981. }
  982. else
  983. {
  984. return "";
  985. }
  986. }
  987. /// <summary>
  988. /// AForge获取麦克风列表
  989. /// </summary>
  990. /// <returns></returns>
  991. public static List<string> GetAudioInDevicesList()
  992. {
  993. List<string> devicesList = new List<string>();
  994. try
  995. {
  996. FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.AudioInputDevice);
  997. foreach (FilterInfo device in videoDevices)
  998. {
  999. devicesList.Add(device.Name);
  1000. }
  1001. }
  1002. catch (ApplicationException)
  1003. {
  1004. //Console.WriteLine("No local capture devices");
  1005. }
  1006. return devicesList;
  1007. }
  1008. /// <summary>
  1009. /// 获取声音输入设备名称 不完整
  1010. /// </summary>
  1011. /// <returns></returns>
  1012. public static string GetInDeviceName()
  1013. {
  1014. List<WaveInCapabilities> devices = new List<WaveInCapabilities>();
  1015. int waveInDevices = WaveIn.DeviceCount;
  1016. for (int i = 0; i < waveInDevices; i++)
  1017. {
  1018. devices.Add(WaveIn.GetCapabilities(i));
  1019. }
  1020. List<string> devs = new List<string>();
  1021. devs = devices.Select(item => item.ProductName).ToList();
  1022. if (devs.Count > 0)
  1023. {
  1024. byte[] buffer = Encoding.UTF8.GetBytes(devs[0]);
  1025. string MicrophoneName = Encoding.UTF8.GetString(buffer); // 统一使用UTF-8
  1026. return MicrophoneName;
  1027. }
  1028. else
  1029. {
  1030. return "";
  1031. }
  1032. }
  1033. /// <summary>
  1034. /// 获取声音输入设备完整名称
  1035. /// </summary>
  1036. /// <returns></returns>
  1037. public static string GetInDeviceFull()
  1038. {
  1039. List<string> devices = new List<string>();
  1040. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  1041. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  1042. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  1043. {
  1044. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  1045. foreach (MMDevice device in deviceCollection)
  1046. {
  1047. try
  1048. {
  1049. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  1050. {
  1051. devices.Add(device.FriendlyName);
  1052. break;
  1053. }
  1054. }
  1055. catch (Exception)
  1056. {
  1057. continue;
  1058. }
  1059. }
  1060. }
  1061. if (devices.Count > 0)
  1062. {
  1063. byte[] buffer = Encoding.UTF8.GetBytes(devices[0]);
  1064. string MicrophoneName = Encoding.UTF8.GetString(buffer); // 统一使用UTF-8
  1065. return MicrophoneName;
  1066. }
  1067. else
  1068. {
  1069. return "";
  1070. }
  1071. }
  1072. /// <summary>
  1073. /// 获取声音输入设备完整名称列表
  1074. /// </summary>
  1075. /// <returns></returns>
  1076. public List<string> GetInDeviceListFull()
  1077. {
  1078. List<string> devices = new List<string>();
  1079. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  1080. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  1081. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  1082. {
  1083. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  1084. foreach (MMDevice device in deviceCollection)
  1085. {
  1086. try
  1087. {
  1088. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  1089. {
  1090. devices.Add(device.FriendlyName);
  1091. break;
  1092. }
  1093. }
  1094. catch (Exception)
  1095. {
  1096. continue;
  1097. }
  1098. }
  1099. }
  1100. return devices;
  1101. }
  1102. /// <summary>
  1103. /// 获取麦克风---废弃
  1104. /// </summary>
  1105. private string GetMicrophone()
  1106. {
  1107. List<string> devs = new List<string>();
  1108. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  1109. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  1110. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  1111. {
  1112. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  1113. foreach (MMDevice device in deviceCollection)
  1114. {
  1115. try
  1116. {
  1117. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  1118. {
  1119. devs.Add(device.FriendlyName);
  1120. break;
  1121. }
  1122. }
  1123. catch (Exception)
  1124. {
  1125. }
  1126. }
  1127. }
  1128. if (devs.Count > 0)
  1129. {
  1130. return devs[0];
  1131. }
  1132. else
  1133. {
  1134. return "";
  1135. }
  1136. }
  1137. #endregion
  1138. #region 检测是否可用
  1139. /// <summary>
  1140. /// 录制麦克风的声音
  1141. /// </summary>
  1142. private WaveInEvent waveIn = null; //new WaveInEvent();
  1143. /// <summary>
  1144. /// 开始录制麦克风
  1145. /// </summary>
  1146. public bool StartRecordAudio(string audioFile)
  1147. {
  1148. try
  1149. {
  1150. waveIn = new WaveInEvent();
  1151. //生成音频文件的对象
  1152. WaveFileWriter writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
  1153. //开始录音,写数据
  1154. waveIn.DataAvailable += (s, a) =>
  1155. {
  1156. writer.Write(a.Buffer, 0, a.BytesRecorded);
  1157. };
  1158. //结束录音
  1159. waveIn.RecordingStopped += (s, a) =>
  1160. {
  1161. writer.Dispose();
  1162. writer = null;
  1163. waveIn.Dispose();
  1164. waveIn = null;
  1165. try
  1166. {
  1167. FileToolsCommon.DeleteFile(audioFile);
  1168. }
  1169. catch (Exception)
  1170. {
  1171. }
  1172. };
  1173. waveIn.StartRecording();
  1174. return true;
  1175. }
  1176. catch (Exception ex)
  1177. {
  1178. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  1179. return false;
  1180. }
  1181. }
  1182. /// <summary>
  1183. /// 结束录制音频
  1184. /// </summary>
  1185. /// <param name="type">1麦克风 2扬声器</param>
  1186. public void StopRecordAudio(int type)
  1187. {
  1188. try
  1189. {
  1190. if (type == 1)
  1191. {
  1192. if (waveIn != null)
  1193. {
  1194. try
  1195. {
  1196. waveIn.StopRecording();
  1197. }
  1198. catch (Exception)
  1199. {
  1200. waveIn = null;
  1201. }
  1202. }
  1203. }
  1204. else if (type == 2)
  1205. {
  1206. if (capture != null)
  1207. {
  1208. try
  1209. {
  1210. capture.StopRecording();
  1211. }
  1212. catch (Exception)
  1213. {
  1214. capture = null;
  1215. }
  1216. }
  1217. }
  1218. }
  1219. catch (Exception ex)
  1220. {
  1221. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  1222. }
  1223. }
  1224. /// <summary>
  1225. /// 录制扬声器的声音
  1226. /// </summary>
  1227. private WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture();
  1228. /// <summary>
  1229. /// 开始录制扬声器
  1230. /// </summary>
  1231. public bool StartRecordSpeakerAudio(string audioFile)
  1232. {
  1233. try
  1234. {
  1235. capture = new WasapiLoopbackCapture();
  1236. //生成音频文件的对象
  1237. WaveFileWriter writer = new WaveFileWriter(audioFile, capture.WaveFormat);
  1238. capture.DataAvailable += (s, a) =>
  1239. {
  1240. writer.Write(a.Buffer, 0, a.BytesRecorded);
  1241. };
  1242. //结束录音
  1243. capture.RecordingStopped += (s, a) =>
  1244. {
  1245. writer.Dispose();
  1246. writer = null;
  1247. capture.Dispose();
  1248. capture = null;
  1249. try
  1250. {
  1251. FileToolsCommon.DeleteFile(audioFile);
  1252. }
  1253. catch (Exception)
  1254. {
  1255. }
  1256. };
  1257. capture.StartRecording();
  1258. return true;
  1259. }
  1260. catch (Exception ex)
  1261. {
  1262. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  1263. return false;
  1264. }
  1265. }
  1266. #endregion
  1267. #endregion
  1268. }
  1269. }