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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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();
  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 (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();
  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. 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. public bool GenerateThumbnails(string VideoPath, string ImagePath)
  551. {
  552. while (myProcess != null)
  553. {
  554. Thread.Sleep(100);
  555. }
  556. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  557. foreach (Process KillProcess in KillProcessArray)
  558. {
  559. KillProcess.Kill();
  560. }
  561. try
  562. {
  563. myProcess = new Process();
  564. LogPath = CreateffmpegLog();
  565. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  566. //myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s " + thubWidth + "*" + thubHeight + " -f image2 \"" + ImagePath + "\"";
  567. myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -f image2 \"" + ImagePath + "\"";
  568. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  569. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  570. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  571. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  572. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  573. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  574. myProcess.Start(); //启动线程
  575. myProcess.BeginErrorReadLine(); //开始异步读取
  576. myProcess.WaitForExit(); //阻塞等待进程结束
  577. myProcess.Close(); //关闭进程
  578. myProcess.Dispose(); //释放资源
  579. #region 进程是否已经释放
  580. bool IsRunning = true;
  581. while (IsRunning)
  582. {
  583. IsRunning = false;
  584. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  585. foreach (Process KillProcess in ProcessArray)
  586. {
  587. IsRunning = true;
  588. Thread.Sleep(100);
  589. }
  590. }
  591. #endregion
  592. myProcess = null;
  593. return true;
  594. }
  595. catch (Exception ex)
  596. {
  597. LogHelper.WriteErrLog("【生成缩略图】(GenerateThumbnails)缩略图生成失败," + ex.Message, ex);
  598. return false;
  599. }
  600. }
  601. /// <summary>
  602. /// 视频转码
  603. /// </summary>
  604. /// <param name="VideoPathName">源视频</param>
  605. /// <param name="VideoSavePathName">目标视频存储路径</param>
  606. /// <param name="Width">宽</param>
  607. /// <param name="Height">高</param>
  608. /// <returns></returns>
  609. public bool VideoTranscode(string VideoPathName, string VideoSavePathName, int Width, int Height)
  610. {
  611. while (myProcess != null)
  612. {
  613. Thread.Sleep(100);
  614. }
  615. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  616. foreach (Process KillProcess in KillProcessArray)
  617. {
  618. KillProcess.Kill();
  619. }
  620. try
  621. {
  622. myProcess = new Process();
  623. LogPath = CreateffmpegLog();
  624. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  625. myProcess.StartInfo.Arguments = "-i " + VideoPathName + " -acodec copy -vcodec libx264 -s " + Width + "*" + Height + " " + VideoSavePathName;
  626. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  627. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  628. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  629. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  630. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  631. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  632. myProcess.Start(); //启动线程
  633. myProcess.BeginErrorReadLine(); //开始异步读取
  634. myProcess.WaitForExit(); //阻塞等待进程结束
  635. myProcess.Close(); //关闭进程
  636. myProcess.Dispose(); //释放资源
  637. #region 进程是否已经释放
  638. bool IsRunning = true;
  639. while (IsRunning)
  640. {
  641. IsRunning = false;
  642. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  643. foreach (Process KillProcess in ProcessArray)
  644. {
  645. IsRunning = true;
  646. Thread.Sleep(100);
  647. }
  648. }
  649. #endregion
  650. myProcess = null;
  651. Thread.Sleep(200);
  652. FileToolsCommon.DeleteFile(VideoPathName);
  653. return true;
  654. }
  655. catch (Exception ex)
  656. {
  657. LogHelper.WriteErrLog("【视频转码】(VideoTranscode)视频转码失败," + ex.Message, ex);
  658. return false;
  659. }
  660. }
  661. /// <summary>
  662. /// 创建日志文件
  663. /// </summary>
  664. /// <returns></returns>
  665. private string CreateffmpegLog()
  666. {
  667. string LogFileName = DateTime.Now.ToString("yyyyMMdd");
  668. string LogFilePath = FileToolsCommon.GetFileAbsolutePath("/Log/FFMpegLog/");
  669. FileToolsCommon.CreateDirectory(LogFilePath);
  670. string LogName = LogFilePath + LogFileName + ".log";
  671. try
  672. {
  673. if (!FileToolsCommon.IsExistFile(LogName))
  674. {
  675. FileToolsCommon.CreateFile(LogName);
  676. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  677. "****************************************************************************************************\r\n");
  678. return LogName;
  679. }
  680. else
  681. {
  682. int num = 0;
  683. while (FileToolsCommon.GetFileSizeByMB(LogName) > 2)
  684. {
  685. num++;
  686. LogName = LogFilePath + LogFileName + "_" + num + ".log";
  687. FileToolsCommon.CreateFile(LogName);
  688. }
  689. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  690. "****************************************************************************************************\r\n");
  691. return LogName;
  692. }
  693. }
  694. catch (Exception)
  695. {
  696. return LogName;
  697. }
  698. }
  699. /// <summary>
  700. /// 输出结果
  701. /// </summary>
  702. /// <param name="sendProcess"></param>
  703. /// <param name="output"></param>
  704. private void Output(object sendProcess, DataReceivedEventArgs output)
  705. {
  706. if (!string.IsNullOrEmpty(output.Data))
  707. {
  708. FileToolsCommon.AppendText(LogPath, output.Data);
  709. }
  710. }
  711. //private void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  712. //{
  713. // //+= new DataReceivedEventHandler((s, message) => { Console.WriteLine(message.Data); })
  714. // using (StreamWriter fs = new StreamWriter("E:\\项目\\测试\\Wpf测试\\bin\\Debug\\ffmpeg\\log.txt", true))
  715. // {
  716. // fs.WriteLine(e.Data);
  717. // Debug.WriteLine(output.Data.ToString());
  718. // }
  719. //}
  720. /// <summary>
  721. /// 获取麦克风
  722. /// </summary>
  723. private string GetMicrophone()
  724. {
  725. List<string> devs = new List<string>();
  726. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  727. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  728. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  729. {
  730. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  731. foreach (MMDevice device in deviceCollection)
  732. {
  733. try
  734. {
  735. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  736. {
  737. devs.Add(device.FriendlyName);
  738. break;
  739. }
  740. }
  741. catch (Exception)
  742. {
  743. }
  744. }
  745. }
  746. if (devs.Count > 0)
  747. {
  748. return devs[0];
  749. }
  750. else
  751. {
  752. return "";
  753. }
  754. }
  755. /// <summary>
  756. /// 获取麦克风列表
  757. /// </summary>
  758. public List<string> GetMicrophoneList()
  759. {
  760. List<string> devs = new List<string>();
  761. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  762. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  763. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  764. {
  765. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  766. foreach (MMDevice device in deviceCollection)
  767. {
  768. try
  769. {
  770. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  771. {
  772. devs.Add(device.FriendlyName);
  773. break;
  774. }
  775. }
  776. catch (Exception)
  777. {
  778. }
  779. }
  780. }
  781. return devs;
  782. }
  783. //录制麦克风的声音
  784. private WaveInEvent waveIn = null; //new WaveInEvent();
  785. /// <summary>
  786. /// 开始录制麦克风
  787. /// </summary>
  788. public bool StartRecordAudio(string audioFile)
  789. {
  790. try
  791. {
  792. waveIn = new WaveInEvent();
  793. //生成音频文件的对象
  794. WaveFileWriter writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
  795. //开始录音,写数据
  796. waveIn.DataAvailable += (s, a) =>
  797. {
  798. writer.Write(a.Buffer, 0, a.BytesRecorded);
  799. };
  800. //结束录音
  801. waveIn.RecordingStopped += (s, a) =>
  802. {
  803. writer.Dispose();
  804. writer = null;
  805. waveIn.Dispose();
  806. waveIn = null;
  807. try
  808. {
  809. FileToolsCommon.DeleteFile(audioFile);
  810. }
  811. catch (Exception)
  812. {
  813. }
  814. };
  815. waveIn.StartRecording();
  816. return true;
  817. }
  818. catch (Exception ex)
  819. {
  820. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  821. return false;
  822. }
  823. }
  824. /// <summary>
  825. /// 结束录制音频
  826. /// </summary>
  827. public void StopRecordAudio()
  828. {
  829. try
  830. {
  831. if (waveIn != null)
  832. {
  833. waveIn.StopRecording();
  834. }
  835. if (capture != null)
  836. {
  837. capture.StopRecording();
  838. }
  839. }
  840. catch (Exception ex)
  841. {
  842. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  843. }
  844. }
  845. //录制扬声器的声音
  846. private WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture();
  847. /// <summary>
  848. /// 开始录制扬声器
  849. /// </summary>
  850. public bool StartRecordSpeakerAudio(string audioFile)
  851. {
  852. try
  853. {
  854. capture = new WasapiLoopbackCapture();
  855. //生成音频文件的对象
  856. WaveFileWriter writer = new WaveFileWriter(audioFile, capture.WaveFormat);
  857. capture.DataAvailable += (s, a) =>
  858. {
  859. writer.Write(a.Buffer, 0, a.BytesRecorded);
  860. };
  861. //结束录音
  862. capture.RecordingStopped += (s, a) =>
  863. {
  864. writer.Dispose();
  865. writer = null;
  866. capture.Dispose();
  867. capture = null;
  868. try
  869. {
  870. FileToolsCommon.DeleteFile(audioFile);
  871. }
  872. catch (Exception)
  873. {
  874. }
  875. };
  876. capture.StartRecording();
  877. return true;
  878. }
  879. catch (Exception ex)
  880. {
  881. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  882. return false;
  883. }
  884. }
  885. }
  886. }