星火微课系统客户端
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

FFMpeg.cs 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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. private string LogPath = "";
  23. /// <summary>
  24. /// 是否可以录制扬声器
  25. /// </summary>
  26. private bool IsRecordSpeaker = true;
  27. /// <summary>
  28. /// 是否可以录制麦克风
  29. /// </summary>
  30. private 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 (Process 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(2);
  75. Thread.Sleep(100);
  76. if (StartRecordAudio(audioMicrophonePath))
  77. {
  78. IsRecordMicrophone = true;
  79. }
  80. else
  81. {
  82. //无法录制麦克风
  83. IsRecordMicrophone = false;
  84. }
  85. StopRecordAudio(1);
  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 (Process 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(2);
  182. Thread.Sleep(100);
  183. if (StartRecordAudio(audioMicrophonePath))
  184. {
  185. IsRecordMicrophone = true;
  186. MicrophoneName = GetMicrophone();
  187. }
  188. else
  189. {
  190. //无法录制麦克风
  191. IsRecordMicrophone = false;
  192. }
  193. StopRecordAudio(1);
  194. if (!IsRecordSpeaker && !IsRecordMicrophone)
  195. {
  196. return false;
  197. }
  198. #endregion
  199. myProcess = new Process();
  200. LogPath = CreateffmpegLog();
  201. 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 (Process 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 (Process 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 bool 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 (Process KillProcess in KillProcessArray)
  312. {
  313. KillProcess.Kill();
  314. }
  315. myProcess = new Process();
  316. try
  317. {
  318. LogPath = CreateffmpegLog();
  319. string mp3Str = "";
  320. #region 判断音频是否存在
  321. if (!string.IsNullOrWhiteSpace(Mp3Path))
  322. {
  323. if (FileToolsCommon.IsExistFile(Mp3Path))
  324. {
  325. mp3Str = "-i " + Mp3Path;
  326. }
  327. }
  328. #endregion
  329. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  330. switch (Extension.ToUpper())
  331. {
  332. case ".MP4":
  333. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  334. ImageListPath + @"%d.png " +
  335. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  336. VideoSavePath;
  337. break;
  338. case ".AVI":
  339. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  340. ImageListPath + @"%d.png " +
  341. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f AVI " +
  342. VideoSavePath;
  343. break;
  344. case ".FLV":
  345. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  346. ImageListPath + @"%d.png " +
  347. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f FLV " +
  348. VideoSavePath;
  349. break;
  350. default:
  351. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  352. ImageListPath + @"%d.png " +
  353. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  354. VideoSavePath;
  355. break;
  356. }
  357. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  358. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  359. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  360. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  361. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  362. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  363. myProcess.Start(); //启动线程
  364. myProcess.BeginErrorReadLine(); //开始异步读取
  365. myProcess.WaitForExit(); //阻塞等待进程结束
  366. myProcess.Close(); //关闭进程
  367. myProcess.Dispose(); //释放资源
  368. #region 进程是否已经释放
  369. bool IsRunning = true;
  370. while (IsRunning)
  371. {
  372. IsRunning = false;
  373. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  374. foreach (Process KillProcess in ProcessArray)
  375. {
  376. IsRunning = true;
  377. Thread.Sleep(100);
  378. }
  379. }
  380. #endregion
  381. myProcess = null;
  382. //生成视频后删除图片和音频保存列表
  383. //FileToolsCommon.DeleteDirectory(ImageListPath);
  384. //FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(Mp3Path));
  385. Thread.Sleep(100);
  386. FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(VideoSavePath) + "temp");
  387. return true;
  388. }
  389. catch (Exception ex)
  390. {
  391. LogHelper.WriteErrLog("【视频合成】(SynthesisVideo)视频生成失败," + ex.Message, ex);
  392. return false;
  393. }
  394. //Dispatcher.Invoke(() =>
  395. //{
  396. //});
  397. //// 允许不同线程间的调用
  398. //Control.CheckForIllegalCrossThreadCalls = false;
  399. }
  400. /// <summary>
  401. /// 视频音频合成
  402. /// </summary>
  403. /// <param name="FilePath">存储路径</param>
  404. public void MergeVideoOrAudio(object FilePathobj)
  405. {
  406. //new Thread(new ThreadStart(new Action(() =>
  407. //{
  408. //Dispatcher.Invoke(() =>
  409. //{
  410. //});
  411. //}))).Start();
  412. while (myProcess != null)
  413. {
  414. Thread.Sleep(100);
  415. }
  416. //路径
  417. string FilePath = (string)FilePathobj;
  418. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  419. //扩展名
  420. string Extension = FileToolsCommon.GetIOExtension(FilePath);
  421. //Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  422. //foreach (var KillProcess in KillProcessArray)
  423. //{
  424. // KillProcess.Kill();
  425. //}
  426. #region 判断文件是否存在
  427. if (Extension.ToUpper() == ".MP3")
  428. {
  429. if (!FileToolsCommon.IsExistFile(Path + "temp/filelist.d"))
  430. {
  431. return;
  432. }
  433. }
  434. else
  435. {
  436. if (!FileToolsCommon.IsExistFile(Path + "temprs/filelist.d"))
  437. {
  438. return;
  439. }
  440. }
  441. #endregion
  442. myProcess = new Process();
  443. LogPath = CreateffmpegLog();
  444. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  445. if (Extension.ToUpper() == ".MP3")
  446. {
  447. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temp/filelist.d -c copy " + FilePath;
  448. }
  449. else
  450. {
  451. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temprs/filelist.d -c copy " + FilePath;
  452. }
  453. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  454. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  455. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  456. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  457. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  458. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  459. myProcess.Start(); //启动线程
  460. myProcess.BeginErrorReadLine(); //开始异步读取
  461. myProcess.WaitForExit(); //阻塞等待进程结束
  462. myProcess.Close(); //关闭进程
  463. myProcess.Dispose(); //释放资源
  464. #region 进程是否已经释放
  465. bool IsRunning = true;
  466. while (IsRunning)
  467. {
  468. IsRunning = false;
  469. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  470. foreach (Process KillProcess in ProcessArray)
  471. {
  472. IsRunning = true;
  473. Thread.Sleep(100);
  474. }
  475. }
  476. #endregion
  477. myProcess = null;
  478. if (Extension.ToUpper() == ".MP3")
  479. {
  480. FileToolsCommon.DeleteDirectory(Path + "temp/");
  481. }
  482. else
  483. {
  484. FileToolsCommon.DeleteDirectory(Path + "temprs/");
  485. }
  486. }
  487. /// <summary>
  488. /// 获取文件完整路径 音频
  489. /// </summary>
  490. /// <param name="FilePath">文件路径</param>
  491. /// <returns></returns>
  492. private string GetFilePathName(string FilePath)
  493. {
  494. //路径
  495. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  496. //Path.GetFileName(FilePath);//获取文件名
  497. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  498. string tempFilePath = Path + "temp/";
  499. //创建临时目录
  500. FileToolsCommon.CreateDirectory(tempFilePath);
  501. //创建记录文件
  502. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  503. {
  504. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  505. }
  506. int num = 1;
  507. string CompleteFilePath = tempFilePath + num + Extension;
  508. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  509. {
  510. num++;
  511. CompleteFilePath = tempFilePath + num + Extension;
  512. }
  513. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  514. return CompleteFilePath;
  515. }
  516. /// <summary>
  517. /// 获取文件完整路径 录屏
  518. /// </summary>
  519. /// <param name="FilePath">文件路径</param>
  520. /// <returns></returns>
  521. private string GetRSFilePathName(string FilePath)
  522. {
  523. //路径
  524. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  525. //Path.GetFileName(FilePath);//获取文件名
  526. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  527. string tempFilePath = Path + "temprs/";
  528. //创建临时目录
  529. FileToolsCommon.CreateDirectory(tempFilePath);
  530. //创建记录文件
  531. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  532. {
  533. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  534. }
  535. int num = 1;
  536. string CompleteFilePath = tempFilePath + num + Extension;
  537. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  538. {
  539. num++;
  540. CompleteFilePath = tempFilePath + num + Extension;
  541. }
  542. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  543. return CompleteFilePath;
  544. }
  545. /// <summary>
  546. /// 生成缩略图
  547. /// </summary>
  548. /// <param name="VideoPath">视频地址</param>
  549. /// <param name="ImagePath">图片地址</param>
  550. /// <param name="Width">图片大小</param>
  551. /// <param name="Height">图片大小</param>
  552. public bool GenerateThumbnails(string VideoPath, string ImagePath,int Width=0,int Height=0)
  553. {
  554. while (myProcess != null)
  555. {
  556. Thread.Sleep(100);
  557. }
  558. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  559. foreach (Process KillProcess in KillProcessArray)
  560. {
  561. KillProcess.Kill();
  562. }
  563. string WHStr = "";
  564. if(Width>0)
  565. {
  566. WHStr = " -s "+ Width + "x"+ Height;
  567. }
  568. try
  569. {
  570. myProcess = new Process();
  571. LogPath = CreateffmpegLog();
  572. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  573. //myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s " + thubWidth + "*" + thubHeight + " -f image2 \"" + ImagePath + "\"";
  574. myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2"+ WHStr + " -f image2 \"" + ImagePath + "\"";
  575. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  576. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  577. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  578. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  579. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  580. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  581. myProcess.Start(); //启动线程
  582. myProcess.BeginErrorReadLine(); //开始异步读取
  583. myProcess.WaitForExit(); //阻塞等待进程结束
  584. myProcess.Close(); //关闭进程
  585. myProcess.Dispose(); //释放资源
  586. #region 进程是否已经释放
  587. bool IsRunning = true;
  588. while (IsRunning)
  589. {
  590. IsRunning = false;
  591. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  592. foreach (Process KillProcess in ProcessArray)
  593. {
  594. IsRunning = true;
  595. Thread.Sleep(100);
  596. }
  597. }
  598. #endregion
  599. myProcess = null;
  600. return true;
  601. }
  602. catch (Exception ex)
  603. {
  604. LogHelper.WriteErrLog("【生成缩略图】(GenerateThumbnails)缩略图生成失败," + ex.Message, ex);
  605. return false;
  606. }
  607. }
  608. /// <summary>
  609. /// 视频转码
  610. /// </summary>
  611. /// <param name="VideoPathName">源视频</param>
  612. /// <param name="VideoSavePathName">目标视频存储路径</param>
  613. /// <param name="Width">宽</param>
  614. /// <param name="Height">高</param>
  615. /// <returns></returns>
  616. public bool VideoTranscode(string VideoPathName, string VideoSavePathName, int Width, int Height)
  617. {
  618. while (myProcess != null)
  619. {
  620. Thread.Sleep(100);
  621. }
  622. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  623. foreach (Process KillProcess in KillProcessArray)
  624. {
  625. KillProcess.Kill();
  626. }
  627. try
  628. {
  629. myProcess = new Process();
  630. LogPath = CreateffmpegLog();
  631. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  632. myProcess.StartInfo.Arguments = "-i " + VideoPathName + " -acodec copy -vcodec libx264 -s " + Width + "*" + Height + " " + VideoSavePathName;
  633. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  634. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  635. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  636. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  637. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  638. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  639. myProcess.Start(); //启动线程
  640. myProcess.BeginErrorReadLine(); //开始异步读取
  641. myProcess.WaitForExit(); //阻塞等待进程结束
  642. myProcess.Close(); //关闭进程
  643. myProcess.Dispose(); //释放资源
  644. #region 进程是否已经释放
  645. bool IsRunning = true;
  646. while (IsRunning)
  647. {
  648. IsRunning = false;
  649. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  650. foreach (Process KillProcess in ProcessArray)
  651. {
  652. IsRunning = true;
  653. Thread.Sleep(100);
  654. }
  655. }
  656. #endregion
  657. myProcess = null;
  658. Thread.Sleep(200);
  659. FileToolsCommon.DeleteFile(VideoPathName);
  660. return true;
  661. }
  662. catch (Exception ex)
  663. {
  664. LogHelper.WriteErrLog("【视频转码】(VideoTranscode)视频转码失败," + ex.Message, ex);
  665. return false;
  666. }
  667. }
  668. /// <summary>
  669. /// 创建日志文件
  670. /// </summary>
  671. /// <returns></returns>
  672. private string CreateffmpegLog()
  673. {
  674. string LogFileName = DateTime.Now.ToString("yyyyMMdd");
  675. string LogFilePath = FileToolsCommon.GetFileAbsolutePath("/Log/FFMpegLog/");
  676. FileToolsCommon.CreateDirectory(LogFilePath);
  677. string LogName = LogFilePath + LogFileName + ".log";
  678. try
  679. {
  680. if (!FileToolsCommon.IsExistFile(LogName))
  681. {
  682. FileToolsCommon.CreateFile(LogName);
  683. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  684. "****************************************************************************************************\r\n");
  685. return LogName;
  686. }
  687. else
  688. {
  689. int num = 0;
  690. while (FileToolsCommon.GetFileSizeByMB(LogName) > 2)
  691. {
  692. num++;
  693. LogName = LogFilePath + LogFileName + "_" + num + ".log";
  694. FileToolsCommon.CreateFile(LogName);
  695. }
  696. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  697. "****************************************************************************************************\r\n");
  698. return LogName;
  699. }
  700. }
  701. catch (Exception)
  702. {
  703. return LogName;
  704. }
  705. }
  706. /// <summary>
  707. /// 输出结果
  708. /// </summary>
  709. /// <param name="sendProcess"></param>
  710. /// <param name="output"></param>
  711. private void Output(object sendProcess, DataReceivedEventArgs output)
  712. {
  713. if (!string.IsNullOrEmpty(output.Data))
  714. {
  715. FileToolsCommon.AppendText(LogPath, output.Data);
  716. }
  717. }
  718. //private void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  719. //{
  720. // //+= new DataReceivedEventHandler((s, message) => { Console.WriteLine(message.Data); })
  721. // using (StreamWriter fs = new StreamWriter("E:\\项目\\测试\\Wpf测试\\bin\\Debug\\ffmpeg\\log.txt", true))
  722. // {
  723. // fs.WriteLine(e.Data);
  724. // Debug.WriteLine(output.Data.ToString());
  725. // }
  726. //}
  727. /// <summary>
  728. /// 获取麦克风
  729. /// </summary>
  730. private string GetMicrophone()
  731. {
  732. List<string> devs = new List<string>();
  733. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  734. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  735. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  736. {
  737. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  738. foreach (MMDevice device in deviceCollection)
  739. {
  740. try
  741. {
  742. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  743. {
  744. devs.Add(device.FriendlyName);
  745. break;
  746. }
  747. }
  748. catch (Exception)
  749. {
  750. }
  751. }
  752. }
  753. if (devs.Count > 0)
  754. {
  755. return devs[0];
  756. }
  757. else
  758. {
  759. return "";
  760. }
  761. }
  762. /// <summary>
  763. /// 获取麦克风列表
  764. /// </summary>
  765. public List<string> GetMicrophoneList()
  766. {
  767. List<string> devs = new List<string>();
  768. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  769. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  770. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  771. {
  772. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  773. foreach (MMDevice device in deviceCollection)
  774. {
  775. try
  776. {
  777. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  778. {
  779. devs.Add(device.FriendlyName);
  780. break;
  781. }
  782. }
  783. catch (Exception)
  784. {
  785. }
  786. }
  787. }
  788. return devs;
  789. }
  790. /// <summary>
  791. /// 录制麦克风的声音
  792. /// </summary>
  793. private WaveInEvent waveIn = null; //new WaveInEvent();
  794. /// <summary>
  795. /// 开始录制麦克风
  796. /// </summary>
  797. public bool StartRecordAudio(string audioFile)
  798. {
  799. try
  800. {
  801. waveIn = new WaveInEvent();
  802. //生成音频文件的对象
  803. WaveFileWriter writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
  804. //开始录音,写数据
  805. waveIn.DataAvailable += (s, a) =>
  806. {
  807. writer.Write(a.Buffer, 0, a.BytesRecorded);
  808. };
  809. //结束录音
  810. waveIn.RecordingStopped += (s, a) =>
  811. {
  812. writer.Dispose();
  813. writer = null;
  814. waveIn.Dispose();
  815. waveIn = null;
  816. try
  817. {
  818. FileToolsCommon.DeleteFile(audioFile);
  819. }
  820. catch (Exception)
  821. {
  822. }
  823. };
  824. waveIn.StartRecording();
  825. return true;
  826. }
  827. catch (Exception ex)
  828. {
  829. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  830. return false;
  831. }
  832. }
  833. /// <summary>
  834. /// 结束录制音频
  835. /// </summary>
  836. /// <param name="type">1麦克风 2扬声器</param>
  837. public void StopRecordAudio(int type)
  838. {
  839. try
  840. {
  841. if (type == 1)
  842. {
  843. if (waveIn != null)
  844. {
  845. try
  846. {
  847. waveIn.StopRecording();
  848. }
  849. catch (Exception)
  850. {
  851. waveIn = null;
  852. }
  853. }
  854. }
  855. else if (type == 2)
  856. {
  857. if (capture != null)
  858. {
  859. try
  860. {
  861. capture.StopRecording();
  862. }
  863. catch (Exception)
  864. {
  865. capture = null;
  866. }
  867. }
  868. }
  869. }
  870. catch (Exception ex)
  871. {
  872. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  873. }
  874. }
  875. /// <summary>
  876. /// 录制扬声器的声音
  877. /// </summary>
  878. private WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture();
  879. /// <summary>
  880. /// 开始录制扬声器
  881. /// </summary>
  882. public bool StartRecordSpeakerAudio(string audioFile)
  883. {
  884. try
  885. {
  886. capture = new WasapiLoopbackCapture();
  887. //生成音频文件的对象
  888. WaveFileWriter writer = new WaveFileWriter(audioFile, capture.WaveFormat);
  889. capture.DataAvailable += (s, a) =>
  890. {
  891. writer.Write(a.Buffer, 0, a.BytesRecorded);
  892. };
  893. //结束录音
  894. capture.RecordingStopped += (s, a) =>
  895. {
  896. writer.Dispose();
  897. writer = null;
  898. capture.Dispose();
  899. capture = null;
  900. try
  901. {
  902. FileToolsCommon.DeleteFile(audioFile);
  903. }
  904. catch (Exception)
  905. {
  906. }
  907. };
  908. capture.StartRecording();
  909. return true;
  910. }
  911. catch (Exception ex)
  912. {
  913. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  914. return false;
  915. }
  916. }
  917. }
  918. }