星火微课系统客户端
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

FFMpeg.cs 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using VisioForge.Shared.NAudio.CoreAudioApi;
  8. using VisioForge.Shared.NAudio.Wave;
  9. namespace Common.system
  10. {
  11. /// <summary>
  12. /// ffmpeg帮助类
  13. /// 需要安装\ffmpeg\bin\Setup Screen Capturer Recorder v0.12.10.exe
  14. /// 本地调试需要配置环境变量 将ffmpeg.exe位置配置到环境变量的path中
  15. /// </summary>
  16. public class FFMpeg
  17. {
  18. Process myProcess = null;
  19. /// <summary>
  20. /// ffmpeg输出日志文件地址 每个文件2MB左右
  21. /// </summary>
  22. string LogPath = "";
  23. /// <summary>
  24. /// 录制屏幕
  25. /// </summary>
  26. /// <param name="PathName">文件存储路径</param>
  27. /// <param name="VideoType">视频类型</param>
  28. public void StartRecordingVideo(string PathName, string VideoType)
  29. {
  30. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  31. Debug.WriteLine(KillProcessArray.Length.ToString());
  32. foreach (var KillProcess in KillProcessArray)
  33. {
  34. KillProcess.Kill();
  35. }
  36. myProcess = new Process();
  37. LogPath = CreateffmpegLog();
  38. string MicrophoneName = GetMicrophone();
  39. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  40. switch (VideoType.ToUpper())
  41. {
  42. case "MP4":
  43. if (string.IsNullOrWhiteSpace(MicrophoneName))
  44. {
  45. 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 avi " + PathName; //ffmpeg的参数
  46. }
  47. else
  48. {
  49. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  50. 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的参数
  51. }
  52. break;
  53. case "AVI":
  54. case "FLV":
  55. if (string.IsNullOrWhiteSpace(MicrophoneName))
  56. {
  57. 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 "+ VideoType.ToLower() + " " + PathName; //ffmpeg的参数
  58. }
  59. else
  60. {
  61. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  62. 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 " + VideoType.ToLower() + " " + PathName; //ffmpeg的参数
  63. }
  64. break;
  65. default:
  66. if (string.IsNullOrWhiteSpace(MicrophoneName))
  67. {
  68. 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 avi " + PathName; //ffmpeg的参数
  69. }
  70. else
  71. {
  72. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  73. 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的参数
  74. }
  75. break;
  76. }
  77. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  78. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  79. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  80. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  81. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  82. myProcess.Start();
  83. myProcess.BeginErrorReadLine();
  84. }
  85. /// <summary>
  86. /// 录制音频
  87. /// </summary>
  88. /// <param name="Mp3Path">MP3音频位置</param>
  89. private void StartRecordingAudio(string Mp3Path)
  90. {
  91. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  92. Debug.WriteLine(KillProcessArray.Length.ToString());
  93. foreach (var KillProcess in KillProcessArray)
  94. {
  95. KillProcess.Kill();
  96. }
  97. myProcess = new Process();
  98. LogPath = CreateffmpegLog();
  99. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  100. string MicrophoneName = GetMicrophone();
  101. if (string.IsNullOrWhiteSpace(MicrophoneName))
  102. {
  103. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" " + Mp3Path;
  104. }
  105. else
  106. {
  107. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  108. MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + Mp3Path;
  109. }
  110. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  111. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  112. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  113. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  114. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  115. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  116. myProcess.Start(); //启动线程
  117. myProcess.BeginErrorReadLine(); //开始异步读取
  118. }
  119. /// <summary>
  120. /// 停止录制
  121. /// </summary>
  122. public void StopFFmpeg()
  123. {
  124. //Thread.Sleep(3000);
  125. if (myProcess == null)
  126. return;
  127. myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
  128. myProcess.Close();//关闭进程
  129. myProcess.Dispose();//释放资源
  130. myProcess = null;
  131. //myProcess.Kill();
  132. }
  133. /// <summary>
  134. /// 合成视频
  135. /// </summary>
  136. /// <param name="ImageListPath">图片列表位置 命名为1.png 2.png</param>
  137. /// <param name="Mp3Path">MP3音频位置</param>
  138. /// <param name="VideoSavePath">视频保存位置</param>
  139. /// <param name="Frequency">每秒帧率</param>
  140. /// <param name="VideoWidth">视频宽度</param>
  141. /// <param name="VideoHeight">视频高度</param>
  142. /// <param name="VideoType">视频类型 MP4 FLV AVI</param>
  143. private void SynthesisVideo(string ImageListPath, string Mp3Path, string VideoSavePath, int Frequency, int VideoWidth, int VideoHeight, string VideoType)
  144. {
  145. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  146. Debug.WriteLine(KillProcessArray.Length.ToString());
  147. foreach (var KillProcess in KillProcessArray)
  148. {
  149. KillProcess.Kill();
  150. }
  151. myProcess = new Process();
  152. LogPath=CreateffmpegLog();
  153. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  154. switch (VideoType.ToUpper())
  155. {
  156. case "MP4":
  157. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  158. ImageListPath + @"%d.png -i " +
  159. Mp3Path + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  160. VideoSavePath;
  161. break;
  162. case "AVI":
  163. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  164. ImageListPath + @"%d.png -i " +
  165. Mp3Path + @" -s " + VideoWidth + "x" + VideoHeight + " -f AVI " +
  166. VideoSavePath;
  167. break;
  168. case "FLV":
  169. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  170. ImageListPath + @"%d.png -i " +
  171. Mp3Path + @" -s " + VideoWidth + "x" + VideoHeight + " -f FLV " +
  172. VideoSavePath;
  173. break;
  174. default:
  175. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  176. ImageListPath + @"%d.png -i " +
  177. Mp3Path + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  178. VideoSavePath;
  179. break;
  180. }
  181. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  182. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  183. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  184. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  185. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  186. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  187. myProcess.Start(); //启动线程
  188. myProcess.BeginErrorReadLine(); //开始异步读取
  189. myProcess.WaitForExit(); //阻塞等待进程结束
  190. myProcess.Close(); //关闭进程
  191. myProcess.Dispose(); //释放资源
  192. //生成视频后删除图片保存列表
  193. FileToolsCommon.DeleteDirectory(ImageListPath);
  194. }
  195. /// <summary>
  196. /// 生成缩略图
  197. /// </summary>
  198. /// <param name="VideoPath">视频地址</param>
  199. /// <param name="ImagePath">图片地址</param>
  200. void GenerateThumbnails(string VideoPath,string ImagePath)
  201. {
  202. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  203. Debug.WriteLine(KillProcessArray.Length.ToString());
  204. foreach (var KillProcess in KillProcessArray)
  205. {
  206. KillProcess.Kill();
  207. }
  208. myProcess = new Process();
  209. LogPath = CreateffmpegLog();
  210. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  211. //myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s " + thubWidth + "*" + thubHeight + " -f image2 \"" + ImagePath + "\"";
  212. myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -f image2 \"" + ImagePath + "\"";
  213. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  214. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  215. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  216. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  217. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  218. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  219. myProcess.Start(); //启动线程
  220. myProcess.BeginErrorReadLine(); //开始异步读取
  221. myProcess.WaitForExit(); //阻塞等待进程结束
  222. myProcess.Close(); //关闭进程
  223. myProcess.Dispose(); //释放资源
  224. }
  225. /// <summary>
  226. /// 创建日志文件
  227. /// </summary>
  228. /// <returns></returns>
  229. string CreateffmpegLog()
  230. {
  231. string LogFileName = DateTime.Now.ToString("yyyyMMdd");
  232. string LogFilePath = FileToolsCommon.GetFileAbsolutePath("/Log/FFMpegLog/");
  233. FileToolsCommon.CreateDirectory(LogFilePath);
  234. string LogName = LogFilePath + LogFileName + ".log";
  235. try
  236. {
  237. if (!FileToolsCommon.IsExistFile(LogName))
  238. {
  239. FileToolsCommon.CreateFile(LogName);
  240. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  241. "****************************************************************************************************\r\n");
  242. return LogName;
  243. }
  244. else
  245. {
  246. int num = 0;
  247. while (FileToolsCommon.GetFileSizeByMB(LogName) > 2)
  248. {
  249. num++;
  250. LogName = LogFilePath + LogFileName + "_" + num + ".log";
  251. FileToolsCommon.CreateFile(LogName);
  252. }
  253. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  254. "****************************************************************************************************\r\n");
  255. return LogName;
  256. }
  257. }
  258. catch (Exception)
  259. {
  260. return LogName;
  261. }
  262. }
  263. /// <summary>
  264. /// 输出结果
  265. /// </summary>
  266. /// <param name="sendProcess"></param>
  267. /// <param name="output"></param>
  268. private void Output(object sendProcess, DataReceivedEventArgs output)
  269. {
  270. if (!String.IsNullOrEmpty(output.Data))
  271. {
  272. FileToolsCommon.AppendText(LogPath, output.Data);
  273. }
  274. }
  275. //private void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  276. //{
  277. // //+= new DataReceivedEventHandler((s, message) => { Console.WriteLine(message.Data); })
  278. // using (StreamWriter fs = new StreamWriter("E:\\项目\\测试\\Wpf测试\\bin\\Debug\\ffmpeg\\log.txt", true))
  279. // {
  280. // fs.WriteLine(e.Data);
  281. // Debug.WriteLine(output.Data.ToString());
  282. // }
  283. //}
  284. /// <summary>
  285. /// 获取麦克风
  286. /// </summary>
  287. string GetMicrophone()
  288. {
  289. List<string> devs = new List<string>();
  290. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  291. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  292. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  293. {
  294. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  295. foreach (MMDevice device in deviceCollection)
  296. {
  297. try
  298. {
  299. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  300. {
  301. devs.Add(device.FriendlyName);
  302. break;
  303. }
  304. }
  305. catch (Exception)
  306. {
  307. }
  308. }
  309. }
  310. if (devs.Count > 0)
  311. {
  312. return devs[0];
  313. }
  314. else
  315. {
  316. return "";
  317. }
  318. }
  319. }
  320. }