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

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