星火微课系统客户端
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 54KB

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