星火微课系统客户端
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Threading;
  5. using VisioForge.Shared.NAudio.CoreAudioApi;
  6. using VisioForge.Shared.NAudio.Wave;
  7. namespace Common.system
  8. {
  9. /// <summary>
  10. /// ffmpeg帮助类
  11. /// 创建人:赵耀
  12. /// 创建时间::2020年8月22日
  13. /// 需要安装\ffmpeg\bin\Setup Screen Capturer Recorder v0.12.10.exe
  14. /// 本地调试需要配置环境变量 将ffmpeg.exe位置配置到环境变量的path中
  15. /// </summary>
  16. public class FFMpeg
  17. {
  18. public Process myProcess = null;
  19. /// <summary>
  20. /// ffmpeg输出日志文件地址 每个文件2MB左右
  21. /// </summary>
  22. string LogPath = "";
  23. /// <summary>
  24. /// 是否可以录制扬声器
  25. /// </summary>
  26. bool IsRecordSpeaker = true;
  27. /// <summary>
  28. /// 是否可以录制麦克风
  29. /// </summary>
  30. bool IsRecordMicrophone = true;
  31. /// <summary>
  32. /// 录制屏幕
  33. /// </summary>
  34. /// <param name="FilePath">文件存储路径</param>
  35. public void StartRecordingVideo(string FilePath)
  36. {
  37. while (myProcess != null)
  38. {
  39. Thread.Sleep(100);
  40. }
  41. //路径
  42. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  43. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  44. //文件保存路径
  45. string PathName = GetRSFilePathName(FilePath);
  46. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  47. foreach (var KillProcess in KillProcessArray)
  48. {
  49. KillProcess.Kill();
  50. }
  51. myProcess = new Process();
  52. LogPath = CreateffmpegLog();
  53. string MicrophoneName = null;
  54. #region 检测麦克风扬声器
  55. string audioSpeakerPath = FileToolsCommon.GetFileAbsolutePath("adoS.m");
  56. string audioMicrophonePath = FileToolsCommon.GetFileAbsolutePath("adoM.m");
  57. try
  58. {
  59. FileToolsCommon.DeleteFile(audioSpeakerPath);
  60. FileToolsCommon.DeleteFile(audioMicrophonePath);
  61. }
  62. catch (Exception)
  63. {
  64. }
  65. if(StartRecordSpeakerAudio(audioSpeakerPath))
  66. {
  67. IsRecordSpeaker = true;
  68. }
  69. else
  70. {
  71. //无法录制扬声器音频
  72. IsRecordSpeaker = false;
  73. }
  74. StopRecordAudio();
  75. Thread.Sleep(500);
  76. if (StartRecordAudio(audioMicrophonePath))
  77. {
  78. IsRecordMicrophone = true;
  79. }
  80. else
  81. {
  82. //无法录制扬声器
  83. IsRecordMicrophone = false;
  84. }
  85. StopRecordAudio();
  86. #endregion
  87. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  88. string SpeakerStr = "";
  89. string MicrophoneStr = "";
  90. if (IsRecordSpeaker)
  91. {
  92. SpeakerStr = "-f dshow -i audio=\"virtual-audio-capturer\" ";
  93. }
  94. if(IsRecordMicrophone)
  95. {
  96. MicrophoneName = GetMicrophone();
  97. if (!string.IsNullOrWhiteSpace(MicrophoneName))
  98. {
  99. MicrophoneStr = "-f dshow -i audio=\"" + MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 ";
  100. }
  101. }
  102. switch (Extension.ToUpper())
  103. {
  104. case ".MP4":
  105. 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;
  106. //if (string.IsNullOrWhiteSpace(MicrophoneName))
  107. //{
  108. // 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的参数
  109. //}
  110. //else
  111. //{
  112. // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  113. // 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的参数
  114. //}
  115. break;
  116. case ".AVI":
  117. case ".FLV":
  118. 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 -f " + Extension.ToLower().Replace(".","") + " " + PathName;
  119. //if (string.IsNullOrWhiteSpace(MicrophoneName))
  120. //{
  121. // 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的参数
  122. //}
  123. //else
  124. //{
  125. // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  126. // 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的参数
  127. //}
  128. break;
  129. default:
  130. 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;
  131. break;
  132. }
  133. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  134. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  135. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  136. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  137. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  138. myProcess.Start();
  139. myProcess.BeginErrorReadLine();
  140. }
  141. /// <summary>
  142. /// 录制音频
  143. /// </summary>
  144. /// <param name="Mp3Path">MP3音频位置</param>
  145. public bool StartRecordingAudio(string Mp3Path)
  146. {
  147. while (myProcess != null)
  148. {
  149. Thread.Sleep(100);
  150. }
  151. //路径
  152. string Path = FileToolsCommon.GetDirectoryName(Mp3Path);
  153. //文件保存路径
  154. string PathName = GetFilePathName(Mp3Path);
  155. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  156. foreach (var KillProcess in KillProcessArray)
  157. {
  158. KillProcess.Kill();
  159. }
  160. string MicrophoneName = null;
  161. #region 检测麦克风扬声器
  162. string audioSpeakerPath = FileToolsCommon.GetFileAbsolutePath("adoS.m");
  163. string audioMicrophonePath = FileToolsCommon.GetFileAbsolutePath("adoM.m");
  164. try
  165. {
  166. FileToolsCommon.DeleteFile(audioSpeakerPath);
  167. FileToolsCommon.DeleteFile(audioMicrophonePath);
  168. }
  169. catch (Exception)
  170. {
  171. }
  172. if (StartRecordSpeakerAudio(audioSpeakerPath))
  173. {
  174. IsRecordSpeaker = true;
  175. }
  176. else
  177. {
  178. //无法录制扬声器音频
  179. IsRecordSpeaker = false;
  180. }
  181. StopRecordAudio();
  182. Thread.Sleep(500);
  183. if (StartRecordAudio(audioMicrophonePath))
  184. {
  185. IsRecordMicrophone = true;
  186. MicrophoneName = GetMicrophone();
  187. }
  188. else
  189. {
  190. //无法录制扬声器
  191. IsRecordMicrophone = false;
  192. }
  193. StopRecordAudio();
  194. if (!IsRecordSpeaker && !IsRecordMicrophone)
  195. {
  196. return false;
  197. }
  198. #endregion
  199. myProcess = new Process();
  200. LogPath = CreateffmpegLog();
  201. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  202. if(IsRecordSpeaker && IsRecordMicrophone)
  203. {
  204. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  205. MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
  206. }
  207. else if(IsRecordSpeaker)
  208. {
  209. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" " + PathName;
  210. }
  211. else if(IsRecordMicrophone)
  212. {
  213. //录制麦克风
  214. if (!string.IsNullOrWhiteSpace(MicrophoneName))
  215. {
  216. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"" +
  217. MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
  218. }
  219. }
  220. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  221. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  222. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  223. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  224. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  225. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  226. myProcess.Start(); //启动线程
  227. myProcess.BeginErrorReadLine(); //开始异步读取
  228. return true;
  229. }
  230. /// <summary>
  231. /// 暂停录制
  232. /// </summary>
  233. public bool SuspendFFmpeg()
  234. {
  235. if (myProcess != null)
  236. {
  237. myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
  238. myProcess.Close();//关闭进程
  239. myProcess.Dispose();//释放资源
  240. }
  241. #region 进程是否已经释放
  242. bool IsRunning = true;
  243. while (IsRunning)
  244. {
  245. IsRunning = false;
  246. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  247. foreach (var KillProcess in ProcessArray)
  248. {
  249. IsRunning = true;
  250. Thread.Sleep(100);
  251. }
  252. }
  253. #endregion
  254. myProcess = null;
  255. return true;
  256. //myProcess.Kill();
  257. }
  258. /// <summary>
  259. /// 停止录制并合成文件
  260. /// </summary>
  261. /// <param name="FilePath">文件存储路径 必须与开始时的路径完全一致</param>
  262. public bool StopFFmpeg(string FilePath)
  263. {
  264. //文件完整路径
  265. if (myProcess != null)
  266. {
  267. myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
  268. myProcess.Close();//关闭进程
  269. myProcess.Dispose();//释放资源
  270. }
  271. #region 进程是否已经释放
  272. bool IsRunning = true;
  273. while (IsRunning)
  274. {
  275. IsRunning = false;
  276. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  277. foreach (var KillProcess in ProcessArray)
  278. {
  279. IsRunning = true;
  280. Thread.Sleep(100);
  281. }
  282. }
  283. #endregion
  284. myProcess = null;
  285. Thread t1 = new Thread(MergeVideoOrAudio);
  286. t1.Start(FilePath);
  287. return true;
  288. //文件合成
  289. }
  290. /// <summary>
  291. /// 图片音频合成视频
  292. /// </summary>
  293. /// <param name="ImageListPath">图片列表位置 命名为1.png 2.png</param>
  294. /// <param name="Mp3Path">MP3音频位置</param>
  295. /// <param name="VideoSavePath">视频保存位置</param>
  296. /// <param name="Frequency">每秒帧率</param>
  297. /// <param name="VideoWidth">视频宽度</param>
  298. /// <param name="VideoHeight">视频高度</param>
  299. public void SynthesisVideo(string ImageListPath, string Mp3Path, string VideoSavePath, int Frequency, int VideoWidth, int VideoHeight)
  300. {
  301. //new Thread(new ThreadStart(new Action(() =>
  302. //{
  303. //}))).Start();
  304. while (myProcess != null)
  305. {
  306. Thread.Sleep(100);
  307. }
  308. string Extension = FileToolsCommon.GetIOExtension(VideoSavePath);//扩展名
  309. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  310. //Debug.WriteLine(KillProcessArray.Length.ToString());
  311. foreach (var KillProcess in KillProcessArray)
  312. {
  313. KillProcess.Kill();
  314. }
  315. myProcess = new Process();
  316. LogPath = CreateffmpegLog();
  317. string mp3Str = "";
  318. #region 判断音频是否存在
  319. if (!string.IsNullOrWhiteSpace(Mp3Path))
  320. {
  321. if (FileToolsCommon.IsExistFile(Mp3Path))
  322. {
  323. mp3Str = "-i " + Mp3Path;
  324. }
  325. }
  326. #endregion
  327. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  328. switch (Extension.ToUpper())
  329. {
  330. case ".MP4":
  331. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  332. ImageListPath + @"%d.png " +
  333. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  334. VideoSavePath;
  335. break;
  336. case ".AVI":
  337. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  338. ImageListPath + @"%d.png " +
  339. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f AVI " +
  340. VideoSavePath;
  341. break;
  342. case ".FLV":
  343. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  344. ImageListPath + @"%d.png " +
  345. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f FLV " +
  346. VideoSavePath;
  347. break;
  348. default:
  349. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  350. ImageListPath + @"%d.png " +
  351. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  352. VideoSavePath;
  353. break;
  354. }
  355. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  356. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  357. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  358. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  359. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  360. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  361. myProcess.Start(); //启动线程
  362. myProcess.BeginErrorReadLine(); //开始异步读取
  363. myProcess.WaitForExit(); //阻塞等待进程结束
  364. myProcess.Close(); //关闭进程
  365. myProcess.Dispose(); //释放资源
  366. #region 进程是否已经释放
  367. bool IsRunning = true;
  368. while (IsRunning)
  369. {
  370. IsRunning = false;
  371. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  372. foreach (var KillProcess in ProcessArray)
  373. {
  374. IsRunning = true;
  375. Thread.Sleep(100);
  376. }
  377. }
  378. #endregion
  379. myProcess = null;
  380. //生成视频后删除图片和音频保存列表
  381. //FileToolsCommon.DeleteDirectory(ImageListPath);
  382. //FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(Mp3Path));
  383. Thread.Sleep(100);
  384. FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(VideoSavePath) + "temp");
  385. //Dispatcher.Invoke(() =>
  386. //{
  387. //});
  388. //// 允许不同线程间的调用
  389. //Control.CheckForIllegalCrossThreadCalls = false;
  390. }
  391. /// <summary>
  392. /// 视频音频合成
  393. /// </summary>
  394. /// <param name="FilePath">存储路径</param>
  395. public void MergeVideoOrAudio(object FilePathobj)
  396. {
  397. //new Thread(new ThreadStart(new Action(() =>
  398. //{
  399. //Dispatcher.Invoke(() =>
  400. //{
  401. //});
  402. //}))).Start();
  403. while (myProcess != null)
  404. {
  405. Thread.Sleep(100);
  406. }
  407. //路径
  408. string FilePath = (string)FilePathobj;
  409. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  410. //扩展名
  411. string Extension = FileToolsCommon.GetIOExtension(FilePath);
  412. //Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  413. //foreach (var KillProcess in KillProcessArray)
  414. //{
  415. // KillProcess.Kill();
  416. //}
  417. #region 判断文件是否存在
  418. if (Extension.ToUpper() == ".MP3")
  419. {
  420. if (!FileToolsCommon.IsExistFile(Path + "temp/filelist.d"))
  421. {
  422. return;
  423. }
  424. }
  425. else
  426. {
  427. if (!FileToolsCommon.IsExistFile(Path + "temprs/filelist.d"))
  428. {
  429. return;
  430. }
  431. }
  432. #endregion
  433. myProcess = new Process();
  434. LogPath = CreateffmpegLog();
  435. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  436. if (Extension.ToUpper() == ".MP3")
  437. {
  438. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temp/filelist.d -c copy " + FilePath;
  439. }
  440. else
  441. {
  442. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temprs/filelist.d -c copy " + FilePath;
  443. }
  444. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  445. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  446. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  447. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  448. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  449. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  450. myProcess.Start(); //启动线程
  451. myProcess.BeginErrorReadLine(); //开始异步读取
  452. myProcess.WaitForExit(); //阻塞等待进程结束
  453. myProcess.Close(); //关闭进程
  454. myProcess.Dispose(); //释放资源
  455. #region 进程是否已经释放
  456. bool IsRunning = true;
  457. while (IsRunning)
  458. {
  459. IsRunning = false;
  460. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  461. foreach (var KillProcess in ProcessArray)
  462. {
  463. IsRunning = true;
  464. Thread.Sleep(100);
  465. }
  466. }
  467. #endregion
  468. myProcess = null;
  469. if (Extension.ToUpper() == ".MP3")
  470. {
  471. FileToolsCommon.DeleteDirectory(Path + "temp/");
  472. }
  473. else
  474. FileToolsCommon.DeleteDirectory(Path + "temprs/");
  475. }
  476. /// <summary>
  477. /// 获取文件完整路径 音频
  478. /// </summary>
  479. /// <param name="FilePath">文件路径</param>
  480. /// <returns></returns>
  481. string GetFilePathName(string FilePath)
  482. {
  483. //路径
  484. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  485. //Path.GetFileName(FilePath);//获取文件名
  486. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  487. string tempFilePath = Path + "temp/";
  488. //创建临时目录
  489. FileToolsCommon.CreateDirectory(tempFilePath);
  490. //创建记录文件
  491. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  492. {
  493. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  494. }
  495. int num = 1;
  496. string CompleteFilePath = tempFilePath + num + Extension;
  497. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  498. {
  499. num++;
  500. CompleteFilePath = tempFilePath + num + Extension;
  501. }
  502. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  503. return CompleteFilePath;
  504. }
  505. /// <summary>
  506. /// 获取文件完整路径 录屏
  507. /// </summary>
  508. /// <param name="FilePath">文件路径</param>
  509. /// <returns></returns>
  510. string GetRSFilePathName(string FilePath)
  511. {
  512. //路径
  513. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  514. //Path.GetFileName(FilePath);//获取文件名
  515. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  516. string tempFilePath = Path + "temprs/";
  517. //创建临时目录
  518. FileToolsCommon.CreateDirectory(tempFilePath);
  519. //创建记录文件
  520. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  521. {
  522. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  523. }
  524. int num = 1;
  525. string CompleteFilePath = tempFilePath + num + Extension;
  526. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  527. {
  528. num++;
  529. CompleteFilePath = tempFilePath + num + Extension;
  530. }
  531. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  532. return CompleteFilePath;
  533. }
  534. /// <summary>
  535. /// 生成缩略图
  536. /// </summary>
  537. /// <param name="VideoPath">视频地址</param>
  538. /// <param name="ImagePath">图片地址</param>
  539. public void GenerateThumbnails(string VideoPath, string ImagePath)
  540. {
  541. while (myProcess != null)
  542. {
  543. Thread.Sleep(100);
  544. }
  545. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  546. foreach (var KillProcess in KillProcessArray)
  547. {
  548. KillProcess.Kill();
  549. }
  550. myProcess = new Process();
  551. LogPath = CreateffmpegLog();
  552. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  553. //myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s " + thubWidth + "*" + thubHeight + " -f image2 \"" + ImagePath + "\"";
  554. myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -f image2 \"" + ImagePath + "\"";
  555. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  556. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  557. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  558. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  559. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  560. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  561. myProcess.Start(); //启动线程
  562. myProcess.BeginErrorReadLine(); //开始异步读取
  563. myProcess.WaitForExit(); //阻塞等待进程结束
  564. myProcess.Close(); //关闭进程
  565. myProcess.Dispose(); //释放资源
  566. #region 进程是否已经释放
  567. bool IsRunning = true;
  568. while (IsRunning)
  569. {
  570. IsRunning = false;
  571. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  572. foreach (var KillProcess in ProcessArray)
  573. {
  574. IsRunning = true;
  575. Thread.Sleep(100);
  576. }
  577. }
  578. #endregion
  579. myProcess = null;
  580. }
  581. /// <summary>
  582. /// 创建日志文件
  583. /// </summary>
  584. /// <returns></returns>
  585. string CreateffmpegLog()
  586. {
  587. string LogFileName = DateTime.Now.ToString("yyyyMMdd");
  588. string LogFilePath = FileToolsCommon.GetFileAbsolutePath("/Log/FFMpegLog/");
  589. FileToolsCommon.CreateDirectory(LogFilePath);
  590. string LogName = LogFilePath + LogFileName + ".log";
  591. try
  592. {
  593. if (!FileToolsCommon.IsExistFile(LogName))
  594. {
  595. FileToolsCommon.CreateFile(LogName);
  596. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  597. "****************************************************************************************************\r\n");
  598. return LogName;
  599. }
  600. else
  601. {
  602. int num = 0;
  603. while (FileToolsCommon.GetFileSizeByMB(LogName) > 2)
  604. {
  605. num++;
  606. LogName = LogFilePath + LogFileName + "_" + num + ".log";
  607. FileToolsCommon.CreateFile(LogName);
  608. }
  609. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  610. "****************************************************************************************************\r\n");
  611. return LogName;
  612. }
  613. }
  614. catch (Exception)
  615. {
  616. return LogName;
  617. }
  618. }
  619. /// <summary>
  620. /// 输出结果
  621. /// </summary>
  622. /// <param name="sendProcess"></param>
  623. /// <param name="output"></param>
  624. private void Output(object sendProcess, DataReceivedEventArgs output)
  625. {
  626. if (!String.IsNullOrEmpty(output.Data))
  627. {
  628. FileToolsCommon.AppendText(LogPath, output.Data);
  629. }
  630. }
  631. //private void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  632. //{
  633. // //+= new DataReceivedEventHandler((s, message) => { Console.WriteLine(message.Data); })
  634. // using (StreamWriter fs = new StreamWriter("E:\\项目\\测试\\Wpf测试\\bin\\Debug\\ffmpeg\\log.txt", true))
  635. // {
  636. // fs.WriteLine(e.Data);
  637. // Debug.WriteLine(output.Data.ToString());
  638. // }
  639. //}
  640. /// <summary>
  641. /// 获取麦克风
  642. /// </summary>
  643. string GetMicrophone()
  644. {
  645. List<string> devs = new List<string>();
  646. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  647. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  648. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  649. {
  650. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  651. foreach (MMDevice device in deviceCollection)
  652. {
  653. try
  654. {
  655. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  656. {
  657. devs.Add(device.FriendlyName);
  658. break;
  659. }
  660. }
  661. catch (Exception)
  662. {
  663. }
  664. }
  665. }
  666. if (devs.Count > 0)
  667. {
  668. return devs[0];
  669. }
  670. else
  671. {
  672. return "";
  673. }
  674. }
  675. /// <summary>
  676. /// 获取麦克风列表
  677. /// </summary>
  678. public List<string> GetMicrophoneList()
  679. {
  680. List<string> devs = new List<string>();
  681. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  682. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  683. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  684. {
  685. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  686. foreach (MMDevice device in deviceCollection)
  687. {
  688. try
  689. {
  690. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  691. {
  692. devs.Add(device.FriendlyName);
  693. break;
  694. }
  695. }
  696. catch (Exception)
  697. {
  698. }
  699. }
  700. }
  701. return devs;
  702. }
  703. //录制麦克风的声音
  704. WaveInEvent waveIn = null; //new WaveInEvent();
  705. /// <summary>
  706. /// 开始录制麦克风
  707. /// </summary>
  708. public bool StartRecordAudio(string audioFile)
  709. {
  710. try
  711. {
  712. waveIn = new WaveInEvent();
  713. //生成音频文件的对象
  714. WaveFileWriter writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
  715. //开始录音,写数据
  716. waveIn.DataAvailable += (s, a) =>
  717. {
  718. writer.Write(a.Buffer, 0, a.BytesRecorded);
  719. };
  720. //结束录音
  721. waveIn.RecordingStopped += (s, a) =>
  722. {
  723. writer.Dispose();
  724. writer = null;
  725. waveIn.Dispose();
  726. waveIn = null;
  727. try
  728. {
  729. FileToolsCommon.DeleteFile(audioFile);
  730. }
  731. catch (Exception)
  732. {
  733. }
  734. };
  735. waveIn.StartRecording();
  736. return true;
  737. }
  738. catch (Exception ex)
  739. {
  740. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  741. return false;
  742. }
  743. }
  744. /// <summary>
  745. /// 结束录制音频
  746. /// </summary>
  747. public void StopRecordAudio()
  748. {
  749. try
  750. {
  751. if (waveIn != null)
  752. {
  753. waveIn.StopRecording();
  754. }
  755. if (capture != null)
  756. {
  757. capture.StopRecording();
  758. }
  759. }
  760. catch (Exception ex)
  761. {
  762. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  763. }
  764. }
  765. //录制扬声器的声音
  766. WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture();
  767. /// <summary>
  768. /// 开始录制扬声器
  769. /// </summary>
  770. public bool StartRecordSpeakerAudio(string audioFile)
  771. {
  772. try
  773. {
  774. capture = new WasapiLoopbackCapture();
  775. //生成音频文件的对象
  776. WaveFileWriter writer = new WaveFileWriter(audioFile, capture.WaveFormat);
  777. capture.DataAvailable += (s, a) =>
  778. {
  779. writer.Write(a.Buffer, 0, a.BytesRecorded);
  780. };
  781. //结束录音
  782. capture.RecordingStopped += (s, a) =>
  783. {
  784. writer.Dispose();
  785. writer = null;
  786. capture.Dispose();
  787. capture = null;
  788. try
  789. {
  790. FileToolsCommon.DeleteFile(audioFile);
  791. }
  792. catch (Exception)
  793. {
  794. }
  795. };
  796. capture.StartRecording();
  797. return true;
  798. }
  799. catch (Exception ex)
  800. {
  801. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  802. return false;
  803. }
  804. }
  805. }
  806. }