星火微课系统客户端
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

FFMpeg.cs 41KB

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