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

пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 3 година
пре 3 година
пре 3 година
пре 4 година
пре 3 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
пре 4 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. using AForge.Video.DirectShow;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using VisioForge.Shared.NAudio.CoreAudioApi;
  10. using VisioForge.Shared.NAudio.Wave;
  11. namespace Common.system
  12. {
  13. /// <summary>
  14. /// ffmpeg帮助类
  15. /// 创建人:赵耀
  16. /// 创建时间::2020年8月22日
  17. /// 需要安装\SSCR\Setup Screen Capturer Recorder v0.12.10.exe
  18. /// 本地调试需要配置环境变量 将ffmpeg.exe位置配置到环境变量的path中
  19. /// </summary>
  20. public class FFMpeg
  21. {
  22. #region 变量
  23. public Process myProcess = null;
  24. /// <summary>
  25. /// 是否输出录课录屏日志
  26. /// </summary>
  27. public bool OutputVideoLog = FileToolsCommon.GetConfigValue("OutputVideoLog") != "0";
  28. /// <summary>
  29. /// ffmpeg输出日志文件地址 每个文件2MB左右
  30. /// </summary>
  31. private string LogPath = "";
  32. /// <summary>
  33. /// 是否可以录制扬声器
  34. /// </summary>
  35. private bool IsRecordSpeaker = true;
  36. /// <summary>
  37. /// 是否可以录制麦克风
  38. /// </summary>
  39. private bool IsRecordMicrophone = true;
  40. #endregion
  41. /// <summary>
  42. /// 录制屏幕
  43. /// </summary>
  44. /// <param name="FilePath">文件存储路径</param>
  45. /// <param name="size">大小</param>
  46. /// <param name="ErrMessage">错误信息</param>
  47. /// <param name="MicrophoneName">麦克风名</param>
  48. /// <returns></returns>
  49. public bool StartRecordingVideo(string FilePath, Size size, out string ErrMessage, string MicrophoneName = null)
  50. {
  51. while (myProcess != null)
  52. {
  53. Thread.Sleep(100);
  54. }
  55. ErrMessage = null;
  56. //路径
  57. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  58. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  59. //文件保存路径
  60. string PathName = GetRSFilePathName(FilePath);
  61. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  62. foreach (Process KillProcess in KillProcessArray)
  63. {
  64. KillProcess.Kill();
  65. }
  66. myProcess = new Process();
  67. LogPath = CreateffmpegLog();
  68. if (string.IsNullOrWhiteSpace(MicrophoneName))
  69. {
  70. MicrophoneName = GetMicrophoneName();
  71. }
  72. #region 检测麦克风扬声器
  73. string AudioPath = FileToolsCommon.GetFileAbsolutePath("/temp/audio/");
  74. FileToolsCommon.CreateDirectory(AudioPath);
  75. string audioSpeakerPath = AudioPath + "adoS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";//FileToolsCommon.GetFileAbsolutePath("adoS.m");
  76. string audioMicrophonePath = AudioPath + "adoM" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";//FileToolsCommon.GetFileAbsolutePath("adoM.m");
  77. try
  78. {
  79. FileToolsCommon.DeleteFile(audioSpeakerPath);
  80. FileToolsCommon.DeleteFile(audioMicrophonePath);
  81. }
  82. catch (Exception)
  83. {
  84. }
  85. if (StartRecordSpeakerAudio(audioSpeakerPath))
  86. {
  87. IsRecordSpeaker = true;
  88. }
  89. else
  90. {
  91. //无法录制扬声器音频
  92. IsRecordSpeaker = false;
  93. }
  94. StopRecordAudio(2);
  95. Thread.Sleep(100);
  96. if (StartRecordAudio(audioMicrophonePath))
  97. {
  98. IsRecordMicrophone = true;
  99. }
  100. else
  101. {
  102. //无法录制麦克风
  103. IsRecordMicrophone = false;
  104. }
  105. StopRecordAudio(1);
  106. #endregion
  107. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  108. string SpeakerStr = "";
  109. string MicrophoneStr = "";
  110. if (IsRecordSpeaker)
  111. {
  112. SpeakerStr = "-f dshow -i audio=\"virtual-audio-capturer\" ";
  113. }
  114. if (IsRecordMicrophone)
  115. {
  116. if (!string.IsNullOrWhiteSpace(MicrophoneName))
  117. {
  118. MicrophoneStr = "-f dshow -i audio=\"" + MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 ";
  119. }
  120. }
  121. switch (Extension.ToUpper())
  122. {
  123. case ".MP4":
  124. myProcess.StartInfo.Arguments = SpeakerStr + MicrophoneStr + " -f gdigrab -framerate 6 -offset_x 0 -offset_y 0 -video_size " + size.Width + "x" + size.Height + " -i desktop -pix_fmt yuv420p -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac " + PathName;
  125. //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;
  126. //if (string.IsNullOrWhiteSpace(MicrophoneName))
  127. //{
  128. // 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的参数
  129. //}
  130. //else
  131. //{
  132. // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  133. // 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的参数
  134. //}
  135. break;
  136. case ".AVI":
  137. case ".FLV":
  138. myProcess.StartInfo.Arguments = SpeakerStr + MicrophoneStr + " -f gdigrab -framerate 6 -offset_x 0 -offset_y 0 -video_size " + size.Width + "x" + size.Height + " -i desktop -pix_fmt yuv420p -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac -f " + Extension.ToLower().Replace(".", "") + " " + PathName;
  139. //if (string.IsNullOrWhiteSpace(MicrophoneName))
  140. //{
  141. // 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的参数
  142. //}
  143. //else
  144. //{
  145. // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  146. // 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的参数
  147. //}
  148. break;
  149. default:
  150. myProcess.StartInfo.Arguments = SpeakerStr + MicrophoneStr + " -f gdigrab -framerate 6 -offset_x 0 -offset_y 0 -video_size " + size.Width + "x" + size.Height + " -i desktop -pix_fmt yuv420p -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac " + PathName;
  151. break;
  152. }
  153. if (OutputVideoLog)
  154. {
  155. LogHelper.WriteInfoLog("【录屏】:" + myProcess.StartInfo.Arguments);
  156. }
  157. FileToolsCommon.AppendText(LogPath, "【录屏】:" + myProcess.StartInfo.Arguments + "\r\n");
  158. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  159. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  160. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  161. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  162. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  163. try
  164. {
  165. myProcess.Start();
  166. myProcess.BeginErrorReadLine();
  167. }
  168. catch (Exception ex)
  169. {
  170. if (ex.Message.Contains("访问"))
  171. {
  172. ErrMessage = "访问被拒绝,请关闭杀毒软件或新任此软件后重试!";
  173. }
  174. else
  175. {
  176. ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
  177. }
  178. LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
  179. myProcess.Dispose();
  180. myProcess = null;
  181. return false;
  182. }
  183. return true;
  184. }
  185. /// <summary>
  186. /// 录制音频
  187. /// </summary>
  188. /// <param name="Mp3Path">MP3音频位置</param>
  189. /// <param name="ErrMessage">错误信息</param>
  190. /// <param name="MicrophoneName">麦克风名</param>
  191. public bool StartRecordingAudio(string Mp3Path, out string ErrMessage, string MicrophoneName = null)
  192. {
  193. ErrMessage = null;
  194. while (myProcess != null)
  195. {
  196. Thread.Sleep(100);
  197. }
  198. //路径
  199. string Path = FileToolsCommon.GetDirectoryName(Mp3Path);
  200. //文件保存路径
  201. string PathName = GetFilePathName(Mp3Path);
  202. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  203. foreach (Process KillProcess in KillProcessArray)
  204. {
  205. KillProcess.Kill();
  206. }
  207. if (string.IsNullOrWhiteSpace(MicrophoneName))
  208. {
  209. MicrophoneName = GetMicrophoneName();
  210. }
  211. #region 检测麦克风扬声器
  212. string AudioPath = FileToolsCommon.GetFileAbsolutePath("/temp/audio/");
  213. FileToolsCommon.CreateDirectory(AudioPath);
  214. string audioSpeakerPath = AudioPath + "adoS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";
  215. string audioMicrophonePath = AudioPath + "adoM" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";
  216. try
  217. {
  218. FileToolsCommon.DeleteFile(audioSpeakerPath);
  219. FileToolsCommon.DeleteFile(audioMicrophonePath);
  220. }
  221. catch (Exception)
  222. {
  223. }
  224. if (StartRecordSpeakerAudio(audioSpeakerPath))
  225. {
  226. IsRecordSpeaker = true;
  227. }
  228. else
  229. {
  230. //无法录制扬声器音频
  231. IsRecordSpeaker = false;
  232. }
  233. StopRecordAudio(2);
  234. Thread.Sleep(100);
  235. if (StartRecordAudio(audioMicrophonePath))
  236. {
  237. IsRecordMicrophone = true;
  238. }
  239. else
  240. {
  241. //无法录制麦克风
  242. IsRecordMicrophone = false;
  243. }
  244. StopRecordAudio(1);
  245. if (!IsRecordSpeaker && !IsRecordMicrophone)
  246. {
  247. ErrMessage = "无法录制声音,请关闭杀毒软件,确保声卡和麦克风处于可用状态!";
  248. return false;
  249. }
  250. #endregion
  251. myProcess = new Process();
  252. LogPath = CreateffmpegLog();
  253. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  254. if (IsRecordSpeaker && IsRecordMicrophone)
  255. {
  256. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
  257. MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
  258. }
  259. else if (IsRecordSpeaker)
  260. {
  261. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" " + PathName;
  262. }
  263. else if (IsRecordMicrophone)
  264. {
  265. //录制麦克风
  266. if (!string.IsNullOrWhiteSpace(MicrophoneName))
  267. {
  268. myProcess.StartInfo.Arguments = "-f dshow -i audio=\"" +
  269. MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
  270. }
  271. }
  272. if (OutputVideoLog)
  273. {
  274. LogHelper.WriteInfoLog("【录音】:" + myProcess.StartInfo.Arguments);
  275. }
  276. FileToolsCommon.AppendText(LogPath, "【录音】:" + myProcess.StartInfo.Arguments + "\r\n");
  277. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  278. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  279. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  280. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  281. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  282. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  283. try
  284. {
  285. myProcess.Start(); //启动线程
  286. myProcess.BeginErrorReadLine(); //开始异步读取
  287. }
  288. catch (Exception ex)
  289. {
  290. if (ex.Message.Contains("访问"))
  291. {
  292. ErrMessage = "无法录制声音,访问被拒绝,请关闭杀毒软件或信任此软件后重试!";
  293. }
  294. else
  295. {
  296. ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
  297. }
  298. LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
  299. myProcess.Dispose();
  300. myProcess = null;
  301. return false;
  302. }
  303. return true;
  304. }
  305. /// <summary>
  306. /// 暂停录制
  307. /// </summary>
  308. public bool SuspendFFmpeg()
  309. {
  310. if (myProcess != null)
  311. {
  312. myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
  313. myProcess.Close();//关闭进程
  314. myProcess.Dispose();//释放资源
  315. }
  316. #region 进程是否已经释放
  317. bool IsRunning = true;
  318. while (IsRunning)
  319. {
  320. IsRunning = false;
  321. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  322. foreach (Process KillProcess in ProcessArray)
  323. {
  324. IsRunning = true;
  325. Thread.Sleep(100);
  326. }
  327. }
  328. #endregion
  329. myProcess = null;
  330. return true;
  331. //myProcess.Kill();
  332. }
  333. /// <summary>
  334. /// 停止录制并合成文件
  335. /// </summary>
  336. /// <param name="FilePath">文件存储路径 必须与开始时的路径完全一致</param>
  337. public bool StopFFmpeg(string FilePath)
  338. {
  339. //文件完整路径
  340. if (myProcess != null)
  341. {
  342. myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
  343. myProcess.Close();//关闭进程
  344. myProcess.Dispose();//释放资源
  345. }
  346. #region 进程是否已经释放
  347. bool IsRunning = true;
  348. while (IsRunning)
  349. {
  350. IsRunning = false;
  351. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  352. foreach (Process KillProcess in ProcessArray)
  353. {
  354. IsRunning = true;
  355. Thread.Sleep(100);
  356. }
  357. }
  358. #endregion
  359. myProcess = null;
  360. Thread t1 = new Thread(MergeVideoOrAudio);
  361. t1.Start(FilePath);
  362. return true;
  363. //文件合成
  364. }
  365. /// <summary>
  366. /// 图片音频合成视频
  367. /// </summary>
  368. /// <param name="ImageListPath">图片列表位置 命名为1.png 2.png</param>
  369. /// <param name="Mp3Path">MP3音频位置</param>
  370. /// <param name="VideoSavePath">视频保存位置</param>
  371. /// <param name="Frequency">每秒帧率</param>
  372. /// <param name="VideoWidth">视频宽度</param>
  373. /// <param name="VideoHeight">视频高度</param>
  374. public bool SynthesisVideo(string ImageListPath, string Mp3Path, string VideoSavePath, int Frequency, int VideoWidth, int VideoHeight, out string ErrMessage)
  375. {
  376. //new Thread(new ThreadStart(new Action(() =>
  377. //{
  378. //}))).Start();
  379. while (myProcess != null)
  380. {
  381. Thread.Sleep(100);
  382. }
  383. ErrMessage = null;
  384. string Extension = FileToolsCommon.GetIOExtension(VideoSavePath);//扩展名
  385. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  386. //Debug.WriteLine(KillProcessArray.Length.ToString());
  387. foreach (Process KillProcess in KillProcessArray)
  388. {
  389. KillProcess.Kill();
  390. }
  391. myProcess = new Process();
  392. try
  393. {
  394. LogPath = CreateffmpegLog();
  395. string mp3Str = "";
  396. #region 判断音频是否存在
  397. if (!string.IsNullOrWhiteSpace(Mp3Path))
  398. {
  399. if (FileToolsCommon.IsExistFile(Mp3Path))
  400. {
  401. mp3Str = "-i " + Mp3Path;
  402. }
  403. }
  404. #endregion
  405. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  406. switch (Extension.ToUpper())
  407. {
  408. case ".MP4":
  409. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  410. ImageListPath + @"%d.png " +
  411. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  412. VideoSavePath;
  413. break;
  414. case ".AVI":
  415. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  416. ImageListPath + @"%d.png " +
  417. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f AVI " +
  418. VideoSavePath;
  419. break;
  420. case ".FLV":
  421. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  422. ImageListPath + @"%d.png " +
  423. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f FLV " +
  424. VideoSavePath;
  425. break;
  426. default:
  427. myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
  428. ImageListPath + @"%d.png " +
  429. mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
  430. VideoSavePath;
  431. break;
  432. }
  433. if (OutputVideoLog)
  434. {
  435. LogHelper.WriteInfoLog("【图片音频合成视频】:" + myProcess.StartInfo.Arguments);
  436. }
  437. FileToolsCommon.AppendText(LogPath, "【图片音频合成视频】:" + myProcess.StartInfo.Arguments + "\r\n");
  438. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  439. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  440. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  441. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  442. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  443. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  444. try
  445. {
  446. myProcess.Start(); //启动线程
  447. myProcess.BeginErrorReadLine(); //开始异步读取
  448. myProcess.WaitForExit(); //阻塞等待进程结束
  449. myProcess.Close(); //关闭进程
  450. }
  451. catch (Exception ex)
  452. {
  453. if (ex.Message.Contains("访问"))
  454. {
  455. ErrMessage = "访问被拒绝,请关闭杀毒软件或新任此软件后重试!";
  456. }
  457. else
  458. {
  459. ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
  460. }
  461. LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
  462. myProcess.Dispose();
  463. myProcess = null;
  464. return false;
  465. }
  466. myProcess.Dispose(); //释放资源
  467. #region 进程是否已经释放
  468. bool IsRunning = true;
  469. while (IsRunning)
  470. {
  471. IsRunning = false;
  472. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  473. foreach (Process KillProcess in ProcessArray)
  474. {
  475. IsRunning = true;
  476. Thread.Sleep(100);
  477. }
  478. }
  479. #endregion
  480. myProcess = null;
  481. //生成视频后删除图片和音频保存列表
  482. //FileToolsCommon.DeleteDirectory(ImageListPath);
  483. //FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(Mp3Path));
  484. Thread.Sleep(100);
  485. FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(VideoSavePath) + "temp");
  486. return true;
  487. }
  488. catch (Exception ex)
  489. {
  490. LogHelper.WriteErrLog("【视频合成】(SynthesisVideo)视频生成失败," + ex.Message, ex);
  491. ErrMessage = ex.Message;
  492. return false;
  493. }
  494. //Dispatcher.Invoke(() =>
  495. //{
  496. //});
  497. //// 允许不同线程间的调用
  498. //Control.CheckForIllegalCrossThreadCalls = false;
  499. }
  500. /// <summary>
  501. /// 视频音频合成
  502. /// </summary>
  503. /// <param name="FilePath">存储路径</param>
  504. public void MergeVideoOrAudio(object FilePathobj)
  505. {
  506. //new Thread(new ThreadStart(new Action(() =>
  507. //{
  508. //Dispatcher.Invoke(() =>
  509. //{
  510. //});
  511. //}))).Start();
  512. while (myProcess != null)
  513. {
  514. Thread.Sleep(100);
  515. }
  516. //路径
  517. string FilePath = (string)FilePathobj;
  518. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  519. //扩展名
  520. string Extension = FileToolsCommon.GetIOExtension(FilePath);
  521. //Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  522. //foreach (var KillProcess in KillProcessArray)
  523. //{
  524. // KillProcess.Kill();
  525. //}
  526. #region 判断文件是否存在
  527. if (Extension.ToUpper() == ".MP3")
  528. {
  529. if (!FileToolsCommon.IsExistFile(Path + "temp/filelist.d"))
  530. {
  531. return;
  532. }
  533. }
  534. else
  535. {
  536. if (!FileToolsCommon.IsExistFile(Path + "temprs/filelist.d"))
  537. {
  538. return;
  539. }
  540. }
  541. #endregion
  542. myProcess = new Process();
  543. LogPath = CreateffmpegLog();
  544. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  545. if (Extension.ToUpper() == ".MP3")
  546. {
  547. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temp/filelist.d -c copy " + FilePath;
  548. }
  549. else
  550. {
  551. myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temprs/filelist.d -c copy " + FilePath;
  552. }
  553. if (OutputVideoLog)
  554. {
  555. LogHelper.WriteInfoLog("【音视频合成】:" + myProcess.StartInfo.Arguments);
  556. }
  557. FileToolsCommon.AppendText(LogPath, "【音视频合成】:" + myProcess.StartInfo.Arguments + "\r\n");
  558. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  559. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  560. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  561. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  562. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  563. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  564. myProcess.Start(); //启动线程
  565. myProcess.BeginErrorReadLine(); //开始异步读取
  566. myProcess.WaitForExit(); //阻塞等待进程结束
  567. myProcess.Close(); //关闭进程
  568. myProcess.Dispose(); //释放资源
  569. #region 进程是否已经释放
  570. bool IsRunning = true;
  571. while (IsRunning)
  572. {
  573. IsRunning = false;
  574. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  575. foreach (Process KillProcess in ProcessArray)
  576. {
  577. IsRunning = true;
  578. Thread.Sleep(100);
  579. }
  580. }
  581. #endregion
  582. myProcess = null;
  583. if (Extension.ToUpper() == ".MP3")
  584. {
  585. FileToolsCommon.DeleteDirectory(Path + "temp/");
  586. }
  587. else
  588. {
  589. FileToolsCommon.DeleteDirectory(Path + "temprs/");
  590. }
  591. }
  592. /// <summary>
  593. /// 视频剪辑
  594. /// </summary>
  595. /// <param name="VideoFilePath">视频路径</param>
  596. /// <param name="StartTime">开始时间 格式 HH:mm:ss</param>
  597. /// <param name="EndTime">结束时间 格式 HH:mm:ss</param>
  598. /// <param name="SaveFilePath">保存文件路径</param>
  599. public void ClipVideo(string VideoFilePath, string StartTime, string EndTime, string SaveFilePath)
  600. {
  601. //new Thread(new ThreadStart(new Action(() =>
  602. //{
  603. //Dispatcher.Invoke(() =>
  604. //{
  605. //});
  606. //}))).Start();
  607. while (myProcess != null)
  608. {
  609. Thread.Sleep(100);
  610. }
  611. //string Path = FileToolsCommon.GetDirectoryName(VideoFilePath);
  612. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  613. foreach (var KillProcess in KillProcessArray)
  614. {
  615. KillProcess.Kill();
  616. }
  617. myProcess = new Process();
  618. LogPath = CreateffmpegLog();
  619. this.myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  620. //ffmpeg -ss 开始时间 -to 结束时间 -accurate_seek -i mp4输入路径 -c:v libx264 -c:a aac -strict experimental -vf scale = 宽:高 -b 500k 输出路径.mp4
  621. myProcess.StartInfo.Arguments = "-i " + VideoFilePath + " -vcodec copy -acodec copy -ss " + StartTime + " -to " + EndTime + " " + SaveFilePath; //-filter:a "volume=0.5"
  622. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  623. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  624. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  625. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  626. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  627. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  628. myProcess.Start(); //启动线程
  629. myProcess.BeginErrorReadLine(); //开始异步读取
  630. myProcess.WaitForExit(); //阻塞等待进程结束
  631. myProcess.Close(); //关闭进程
  632. myProcess.Dispose(); //释放资源
  633. #region 进程是否已经释放
  634. bool IsRunning = true;
  635. while (IsRunning)
  636. {
  637. IsRunning = false;
  638. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  639. foreach (var KillProcess in ProcessArray)
  640. {
  641. IsRunning = true;
  642. Thread.Sleep(100);
  643. }
  644. }
  645. #endregion
  646. myProcess = null;
  647. }
  648. /// <summary>
  649. /// 获取文件完整路径 音频
  650. /// </summary>
  651. /// <param name="FilePath">文件路径</param>
  652. /// <returns></returns>
  653. private string GetFilePathName(string FilePath)
  654. {
  655. //路径
  656. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  657. //Path.GetFileName(FilePath);//获取文件名
  658. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  659. string tempFilePath = Path + "temp/";
  660. //创建临时目录
  661. FileToolsCommon.CreateDirectory(tempFilePath);
  662. //创建记录文件
  663. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  664. {
  665. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  666. }
  667. int num = 1;
  668. string CompleteFilePath = tempFilePath + num + Extension;
  669. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  670. {
  671. num++;
  672. CompleteFilePath = tempFilePath + num + Extension;
  673. }
  674. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  675. return CompleteFilePath;
  676. }
  677. /// <summary>
  678. /// 获取文件完整路径 录屏
  679. /// </summary>
  680. /// <param name="FilePath">文件路径</param>
  681. /// <returns></returns>
  682. private string GetRSFilePathName(string FilePath)
  683. {
  684. //路径
  685. string Path = FileToolsCommon.GetDirectoryName(FilePath);
  686. //Path.GetFileName(FilePath);//获取文件名
  687. string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
  688. string tempFilePath = Path + "temprs/";
  689. //创建临时目录
  690. FileToolsCommon.CreateDirectory(tempFilePath);
  691. //创建记录文件
  692. if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
  693. {
  694. FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
  695. }
  696. int num = 1;
  697. string CompleteFilePath = tempFilePath + num + Extension;
  698. while (FileToolsCommon.IsExistFile(CompleteFilePath))
  699. {
  700. num++;
  701. CompleteFilePath = tempFilePath + num + Extension;
  702. }
  703. FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
  704. return CompleteFilePath;
  705. }
  706. /// <summary>
  707. /// 生成缩略图
  708. /// </summary>
  709. /// <param name="VideoPath">视频地址</param>
  710. /// <param name="ImagePath">图片地址</param>
  711. /// <param name="Width">图片大小</param>
  712. /// <param name="Height">图片大小</param>
  713. public bool GenerateThumbnails(string VideoPath, string ImagePath, int Width = 0, int Height = 0)
  714. {
  715. while (myProcess != null)
  716. {
  717. Thread.Sleep(100);
  718. }
  719. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  720. foreach (Process KillProcess in KillProcessArray)
  721. {
  722. KillProcess.Kill();
  723. }
  724. string WHStr = "";
  725. if (Width > 0)
  726. {
  727. WHStr = " -s " + Width + "x" + Height;
  728. }
  729. try
  730. {
  731. myProcess = new Process();
  732. LogPath = CreateffmpegLog();
  733. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  734. //myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s " + thubWidth + "*" + thubHeight + " -f image2 \"" + ImagePath + "\"";
  735. myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2" + WHStr + " -f image2 \"" + ImagePath + "\"";
  736. if (OutputVideoLog)
  737. {
  738. LogHelper.WriteInfoLog("【生成缩略图】:" + myProcess.StartInfo.Arguments);
  739. }
  740. FileToolsCommon.AppendText(LogPath, "【生成缩略图】:" + myProcess.StartInfo.Arguments + "\r\n");
  741. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  742. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  743. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  744. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  745. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  746. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  747. myProcess.Start(); //启动线程
  748. myProcess.BeginErrorReadLine(); //开始异步读取
  749. myProcess.WaitForExit(); //阻塞等待进程结束
  750. myProcess.Close(); //关闭进程
  751. myProcess.Dispose(); //释放资源
  752. #region 进程是否已经释放
  753. bool IsRunning = true;
  754. while (IsRunning)
  755. {
  756. IsRunning = false;
  757. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  758. foreach (Process KillProcess in ProcessArray)
  759. {
  760. IsRunning = true;
  761. Thread.Sleep(100);
  762. }
  763. }
  764. #endregion
  765. myProcess = null;
  766. return true;
  767. }
  768. catch (Exception ex)
  769. {
  770. LogHelper.WriteErrLog("【生成缩略图】(GenerateThumbnails)缩略图生成失败," + ex.Message, ex);
  771. return false;
  772. }
  773. }
  774. /// <summary>
  775. /// 视频转码
  776. /// </summary>
  777. /// <param name="VideoPathName">源视频</param>
  778. /// <param name="VideoSavePathName">目标视频存储路径</param>
  779. /// <param name="Width">宽</param>
  780. /// <param name="Height">高</param>
  781. /// <returns></returns>
  782. public bool VideoTranscode(string VideoPathName, string VideoSavePathName, int Width, int Height)
  783. {
  784. while (myProcess != null)
  785. {
  786. Thread.Sleep(100);
  787. }
  788. Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
  789. foreach (Process KillProcess in KillProcessArray)
  790. {
  791. KillProcess.Kill();
  792. }
  793. try
  794. {
  795. myProcess = new Process();
  796. LogPath = CreateffmpegLog();
  797. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  798. myProcess.StartInfo.Arguments = "-i " + VideoPathName + " -acodec copy -vcodec libx264 -s " + Width + "*" + Height + " " + VideoSavePathName;
  799. if (OutputVideoLog)
  800. {
  801. LogHelper.WriteInfoLog("【视频转码】:" + myProcess.StartInfo.Arguments);
  802. }
  803. FileToolsCommon.AppendText(LogPath, "【视频转码】:" + myProcess.StartInfo.Arguments + "\r\n");
  804. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  805. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  806. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  807. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  808. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  809. myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
  810. myProcess.Start(); //启动线程
  811. myProcess.BeginErrorReadLine(); //开始异步读取
  812. myProcess.WaitForExit(); //阻塞等待进程结束
  813. myProcess.Close(); //关闭进程
  814. myProcess.Dispose(); //释放资源
  815. #region 进程是否已经释放
  816. bool IsRunning = true;
  817. while (IsRunning)
  818. {
  819. IsRunning = false;
  820. Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
  821. foreach (Process KillProcess in ProcessArray)
  822. {
  823. IsRunning = true;
  824. Thread.Sleep(100);
  825. }
  826. }
  827. #endregion
  828. myProcess = null;
  829. Thread.Sleep(200);
  830. FileToolsCommon.DeleteFile(VideoPathName);
  831. return true;
  832. }
  833. catch (Exception ex)
  834. {
  835. LogHelper.WriteErrLog("【视频转码】(VideoTranscode)视频转码失败," + ex.Message, ex);
  836. return false;
  837. }
  838. }
  839. /// <summary>
  840. /// 创建日志文件
  841. /// </summary>
  842. /// <returns></returns>
  843. private string CreateffmpegLog()
  844. {
  845. string LogFileName = DateTime.Now.ToString("yyyyMMdd");
  846. string LogFilePath = FileToolsCommon.GetFileAbsolutePath("/Log/FFMpegLog/");
  847. FileToolsCommon.CreateDirectory(LogFilePath);
  848. string LogName = LogFilePath + LogFileName + ".log";
  849. try
  850. {
  851. if (!FileToolsCommon.IsExistFile(LogName))
  852. {
  853. FileToolsCommon.CreateFile(LogName);
  854. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  855. "****************************************************************************************************\r\n");
  856. return LogName;
  857. }
  858. else
  859. {
  860. int num = 0;
  861. while (FileToolsCommon.GetFileSizeByMB(LogName) > 2)
  862. {
  863. num++;
  864. LogName = LogFilePath + LogFileName + "_" + num + ".log";
  865. FileToolsCommon.CreateFile(LogName);
  866. }
  867. FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
  868. "****************************************************************************************************\r\n");
  869. return LogName;
  870. }
  871. }
  872. catch (Exception)
  873. {
  874. return LogName;
  875. }
  876. }
  877. /// <summary>
  878. /// 输出结果
  879. /// </summary>
  880. /// <param name="sendProcess"></param>
  881. /// <param name="output"></param>
  882. private void Output(object sendProcess, DataReceivedEventArgs output)
  883. {
  884. if (!string.IsNullOrEmpty(output.Data))
  885. {
  886. FileToolsCommon.AppendText(LogPath, "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "】:");
  887. FileToolsCommon.AppendText(LogPath, output.Data + "\r\n");
  888. }
  889. }
  890. #region 麦克风声卡检测
  891. #region 获取麦克风
  892. private bool IsMicrophone = false;
  893. /// <summary>
  894. /// 使用FFmpeg获取的麦克风名
  895. /// </summary>
  896. private string MicrophoneNameInfo = "";
  897. /// <summary>
  898. /// 获取麦克风名称
  899. /// </summary>
  900. /// <returns></returns>
  901. public string GetMicrophoneName()
  902. {
  903. return GetAudioInDevices();
  904. //string FullName = GetInDeviceFull();
  905. //if(string.IsNullOrWhiteSpace(MicrophoneNameInfo))
  906. //{
  907. // return FullName;
  908. //}
  909. ////byte[] bufferASCII = Encoding.Default.GetBytes(MicrophoneNameInfo);
  910. ////string str = Encoding.UTF8.GetString(bufferASCII);
  911. ////str = str.Replace("?", " ");
  912. ////int num = str.Length;
  913. ////int num1 = FullName.Length;
  914. //if (FullName.Contains("(") || FullName.Contains("("))
  915. //{
  916. // string EName = FullName.Substring(FullName.IndexOf("(")+1);
  917. // if(string.IsNullOrEmpty(EName))
  918. // {
  919. // EName = FullName.Substring(FullName.IndexOf("(") + 1);
  920. // EName = EName.Substring(0, EName.LastIndexOf(")"));
  921. // }
  922. // else
  923. // {
  924. // //EName = EName.Substring(0, EName.LastIndexOf(")"));
  925. // }
  926. // if(MicrophoneNameInfo.Contains(EName))
  927. // {
  928. // return FullName;
  929. // }
  930. // else
  931. // {
  932. // return GetInDeviceName();
  933. // }
  934. //}
  935. //else
  936. //{
  937. // return FullName;
  938. //}
  939. }
  940. /// <summary>
  941. /// 获取麦克风列表
  942. /// </summary>
  943. /// <returns></returns>
  944. public List<string> GetMicrophoneNameList()
  945. {
  946. return GetAudioInDevicesList();
  947. }
  948. /// <summary>
  949. /// 使用FFmpeg获取设备名称--待定
  950. /// </summary>
  951. public void GetMToFFmpeg()
  952. {
  953. //return;
  954. new Thread(new ThreadStart(new Action(() =>
  955. {
  956. try
  957. {
  958. while (myProcess != null)
  959. {
  960. Thread.Sleep(100);
  961. }
  962. myProcess = new Process();
  963. LogPath = CreateffmpegLog();
  964. myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
  965. myProcess.StartInfo.Arguments = " -list_devices true -f dshow -i dummy";
  966. if (OutputVideoLog)
  967. {
  968. LogHelper.WriteInfoLog("【获取设备信息】:" + myProcess.StartInfo.Arguments);
  969. }
  970. FileToolsCommon.AppendText(LogPath, "【获取设备信息】:" + myProcess.StartInfo.Arguments + "\r\n");
  971. myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
  972. myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  973. myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
  974. myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
  975. //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
  976. myProcess.ErrorDataReceived += GetDevInfoData;
  977. myProcess.Start(); //启动线程
  978. myProcess.BeginErrorReadLine(); //开始异步读取
  979. myProcess.WaitForExit(); //阻塞等待进程结束
  980. myProcess.Close(); //关闭进程
  981. myProcess.Dispose(); //释放资源
  982. myProcess = null;
  983. }
  984. catch (Exception ex)
  985. {
  986. LogHelper.WriteErrLog("【获取设备信息】(GetMToFFmpeg)信息获取失败:" + ex.Message, ex);
  987. }
  988. }))).Start();
  989. }
  990. /// <summary>
  991. /// 使用FFmpeg获取设备名称--待定
  992. /// </summary>
  993. /// <param name="sender"></param>
  994. /// <param name="e"></param>
  995. private void GetDevInfoData(object sender, DataReceivedEventArgs e)
  996. {
  997. if (!string.IsNullOrEmpty(e.Data))
  998. {
  999. if (IsMicrophone)
  1000. {
  1001. try
  1002. {
  1003. MicrophoneNameInfo = e.Data;
  1004. MicrophoneNameInfo = MicrophoneNameInfo.Substring(MicrophoneNameInfo.IndexOf("]") + 1);
  1005. MicrophoneNameInfo = MicrophoneNameInfo.Replace("\"", "");
  1006. MicrophoneNameInfo = MicrophoneNameInfo.Trim();
  1007. #region 测试
  1008. //byte[] bufferASCII = Encoding.Default.GetBytes(MicrophoneNameInfo);
  1009. //MicrophoneNameInfo = Encoding.UTF8.GetString(bufferASCII); // 统一使用UTF-8
  1010. ////System.Text.Encoding GB2312 = System.Text.Encoding.GetEncoding("GB2312");
  1011. ////byte[] gb = GB2312.GetBytes(MicrophoneNameInfo);
  1012. ////MicrophoneNameInfo = Encoding.UTF8.GetString(gb);
  1013. #endregion
  1014. IsMicrophone = false;
  1015. FileToolsCommon.AppendText(LogPath, e.Data);
  1016. //FileToolsCommon.AppendText(LogPath, "\r\n***************************************************\r\n");
  1017. }
  1018. catch (Exception ex)
  1019. {
  1020. LogHelper.WriteErrLog("【获取设备信息】(GetDevInfoData)信息获取失败:" + ex.Message, ex);
  1021. }
  1022. }
  1023. else
  1024. {
  1025. if (e.Data.Contains("DirectShow audio devices"))
  1026. {
  1027. //FileToolsCommon.AppendText(LogPath, "\r\n***************************************************\r\n");
  1028. IsMicrophone = true;
  1029. }
  1030. FileToolsCommon.AppendText(LogPath, e.Data);
  1031. FileToolsCommon.AppendText(LogPath, "\r\n");
  1032. }
  1033. }
  1034. }
  1035. /// <summary>
  1036. /// AForge获取麦克风
  1037. /// </summary>
  1038. /// <returns></returns>
  1039. public static string GetAudioInDevices()
  1040. {
  1041. List<string> devicesList = new List<string>();
  1042. try
  1043. {
  1044. FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.AudioInputDevice);
  1045. foreach (FilterInfo device in videoDevices)
  1046. {
  1047. devicesList.Add(device.Name);
  1048. }
  1049. }
  1050. catch (ApplicationException)
  1051. {
  1052. //Console.WriteLine("No local capture devices");
  1053. }
  1054. if (devicesList.Count > 1)
  1055. {
  1056. return devicesList[1];
  1057. }
  1058. else
  1059. {
  1060. return "";
  1061. }
  1062. }
  1063. /// <summary>
  1064. /// AForge获取麦克风列表
  1065. /// </summary>
  1066. /// <returns></returns>
  1067. public static List<string> GetAudioInDevicesList()
  1068. {
  1069. List<string> devicesList = new List<string>();
  1070. try
  1071. {
  1072. FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.AudioInputDevice);
  1073. foreach (FilterInfo device in videoDevices)
  1074. {
  1075. if (device.Name == "virtual-audio-capturer")
  1076. {
  1077. continue;
  1078. }
  1079. devicesList.Add(device.Name);
  1080. }
  1081. }
  1082. catch (ApplicationException)
  1083. {
  1084. //Console.WriteLine("No local capture devices");
  1085. }
  1086. return devicesList;
  1087. }
  1088. /// <summary>
  1089. /// 获取声音输入设备名称 不完整
  1090. /// </summary>
  1091. /// <returns></returns>
  1092. public static string GetInDeviceName()
  1093. {
  1094. List<WaveInCapabilities> devices = new List<WaveInCapabilities>();
  1095. int waveInDevices = WaveIn.DeviceCount;
  1096. for (int i = 0; i < waveInDevices; i++)
  1097. {
  1098. devices.Add(WaveIn.GetCapabilities(i));
  1099. }
  1100. List<string> devs = new List<string>();
  1101. devs = devices.Select(item => item.ProductName).ToList();
  1102. if (devs.Count > 0)
  1103. {
  1104. byte[] buffer = Encoding.UTF8.GetBytes(devs[0]);
  1105. string MicrophoneName = Encoding.UTF8.GetString(buffer); // 统一使用UTF-8
  1106. return MicrophoneName;
  1107. }
  1108. else
  1109. {
  1110. return "";
  1111. }
  1112. }
  1113. /// <summary>
  1114. /// 获取声音输入设备完整名称
  1115. /// </summary>
  1116. /// <returns></returns>
  1117. public static string GetInDeviceFull()
  1118. {
  1119. List<string> devices = new List<string>();
  1120. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  1121. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  1122. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  1123. {
  1124. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  1125. foreach (MMDevice device in deviceCollection)
  1126. {
  1127. try
  1128. {
  1129. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  1130. {
  1131. devices.Add(device.FriendlyName);
  1132. break;
  1133. }
  1134. }
  1135. catch (Exception)
  1136. {
  1137. continue;
  1138. }
  1139. }
  1140. }
  1141. if (devices.Count > 0)
  1142. {
  1143. byte[] buffer = Encoding.UTF8.GetBytes(devices[0]);
  1144. string MicrophoneName = Encoding.UTF8.GetString(buffer); // 统一使用UTF-8
  1145. return MicrophoneName;
  1146. }
  1147. else
  1148. {
  1149. return "";
  1150. }
  1151. }
  1152. /// <summary>
  1153. /// 获取声音输入设备完整名称列表
  1154. /// </summary>
  1155. /// <returns></returns>
  1156. public List<string> GetInDeviceListFull()
  1157. {
  1158. List<string> devices = new List<string>();
  1159. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  1160. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  1161. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  1162. {
  1163. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  1164. foreach (MMDevice device in deviceCollection)
  1165. {
  1166. try
  1167. {
  1168. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  1169. {
  1170. devices.Add(device.FriendlyName);
  1171. break;
  1172. }
  1173. }
  1174. catch (Exception)
  1175. {
  1176. continue;
  1177. }
  1178. }
  1179. }
  1180. return devices;
  1181. }
  1182. /// <summary>
  1183. /// 获取麦克风---废弃
  1184. /// </summary>
  1185. private string GetMicrophone()
  1186. {
  1187. List<string> devs = new List<string>();
  1188. MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
  1189. MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
  1190. for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
  1191. {
  1192. WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
  1193. foreach (MMDevice device in deviceCollection)
  1194. {
  1195. try
  1196. {
  1197. if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
  1198. {
  1199. devs.Add(device.FriendlyName);
  1200. break;
  1201. }
  1202. }
  1203. catch (Exception)
  1204. {
  1205. }
  1206. }
  1207. }
  1208. if (devs.Count > 0)
  1209. {
  1210. return devs[0];
  1211. }
  1212. else
  1213. {
  1214. return "";
  1215. }
  1216. }
  1217. #endregion
  1218. #region 录音
  1219. /// <summary>
  1220. /// 开始录制麦克风
  1221. /// </summary>
  1222. public bool StartAudio(string audioFile, string DeviceName = "")
  1223. {
  1224. try
  1225. {
  1226. int deviceIndex = 0;
  1227. waveIn = new WaveInEvent();
  1228. List<string> InDeviceList = GetInDeviceListFull();
  1229. if (InDeviceList.Exists(x => DeviceName.Contains(x)))
  1230. {
  1231. deviceIndex = InDeviceList.FindIndex(x => DeviceName.Contains(x));
  1232. }
  1233. waveIn.DeviceNumber = deviceIndex;
  1234. //waveIn.DeviceNumber = 1;
  1235. //生成音频文件的对象
  1236. WaveFileWriter writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
  1237. //开始录音,写数据
  1238. waveIn.DataAvailable += (s, a) =>
  1239. {
  1240. writer.Write(a.Buffer, 0, a.BytesRecorded);
  1241. };
  1242. return true;
  1243. }
  1244. catch (Exception ex)
  1245. {
  1246. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  1247. return false;
  1248. }
  1249. }
  1250. //public bool StopAudio()
  1251. //{
  1252. // try
  1253. // {
  1254. // //结束录音
  1255. // waveIn.RecordingStopped += (s, a) =>
  1256. // {
  1257. // writer.Dispose();
  1258. // writer = null;
  1259. // waveIn.Dispose();
  1260. // waveIn = null;
  1261. // try
  1262. // {
  1263. // FileToolsCommon.DeleteFile(audioFile);
  1264. // }
  1265. // catch (Exception)
  1266. // {
  1267. // }
  1268. // };
  1269. // waveIn.StartRecording();
  1270. // }
  1271. // catch (Exception ex)
  1272. // {
  1273. // throw;
  1274. // }
  1275. //}
  1276. #endregion
  1277. #region 检测是否可用
  1278. /// <summary>
  1279. /// 录制麦克风的声音
  1280. /// </summary>
  1281. private WaveInEvent waveIn = null; //new WaveInEvent();
  1282. /// <summary>
  1283. /// 开始录制麦克风
  1284. /// </summary>
  1285. public bool StartRecordAudio(string audioFile, string DeviceName = "", bool IsStopDelFile=true)
  1286. {
  1287. try
  1288. {
  1289. int deviceIndex = 0;
  1290. waveIn = new WaveInEvent();
  1291. List<string> InDeviceList = GetInDeviceListFull();
  1292. if (InDeviceList.Exists(x => DeviceName.Contains(x)))
  1293. {
  1294. deviceIndex = InDeviceList.FindIndex(x => DeviceName.Contains(x));
  1295. }
  1296. waveIn.DeviceNumber = deviceIndex;
  1297. //waveIn.DeviceNumber = 1;
  1298. //生成音频文件的对象
  1299. WaveFileWriter writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
  1300. //开始录音,写数据
  1301. waveIn.DataAvailable += (s, a) =>
  1302. {
  1303. writer.Write(a.Buffer, 0, a.BytesRecorded);
  1304. };
  1305. //结束录音
  1306. waveIn.RecordingStopped += (s, a) =>
  1307. {
  1308. writer.Dispose();
  1309. writer = null;
  1310. waveIn.Dispose();
  1311. waveIn = null;
  1312. try
  1313. {
  1314. if (IsStopDelFile)
  1315. {
  1316. FileToolsCommon.DeleteFile(audioFile);
  1317. }
  1318. }
  1319. catch (Exception)
  1320. {
  1321. }
  1322. };
  1323. waveIn.StartRecording();
  1324. return true;
  1325. }
  1326. catch (Exception ex)
  1327. {
  1328. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  1329. return false;
  1330. }
  1331. }
  1332. /// <summary>
  1333. /// 结束录制音频
  1334. /// </summary>
  1335. /// <param name="type">1麦克风 2扬声器</param>
  1336. public void StopRecordAudio(int type)
  1337. {
  1338. try
  1339. {
  1340. if (type == 1)
  1341. {
  1342. if (waveIn != null)
  1343. {
  1344. try
  1345. {
  1346. waveIn.StopRecording();
  1347. }
  1348. catch (Exception)
  1349. {
  1350. waveIn = null;
  1351. }
  1352. }
  1353. }
  1354. else if (type == 2)
  1355. {
  1356. if (capture != null)
  1357. {
  1358. try
  1359. {
  1360. capture.StopRecording();
  1361. }
  1362. catch (Exception)
  1363. {
  1364. capture = null;
  1365. }
  1366. }
  1367. }
  1368. }
  1369. catch (Exception ex)
  1370. {
  1371. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  1372. }
  1373. }
  1374. /// <summary>
  1375. /// 录制扬声器的声音
  1376. /// </summary>
  1377. private WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture();
  1378. /// <summary>
  1379. /// 开始录制扬声器
  1380. /// </summary>
  1381. public bool StartRecordSpeakerAudio(string audioFile)
  1382. {
  1383. try
  1384. {
  1385. capture = new WasapiLoopbackCapture();
  1386. //生成音频文件的对象
  1387. WaveFileWriter writer = new WaveFileWriter(audioFile, capture.WaveFormat);
  1388. capture.DataAvailable += (s, a) =>
  1389. {
  1390. writer.Write(a.Buffer, 0, a.BytesRecorded);
  1391. };
  1392. //结束录音
  1393. capture.RecordingStopped += (s, a) =>
  1394. {
  1395. writer.Dispose();
  1396. writer = null;
  1397. capture.Dispose();
  1398. capture = null;
  1399. try
  1400. {
  1401. FileToolsCommon.DeleteFile(audioFile);
  1402. }
  1403. catch (Exception)
  1404. {
  1405. }
  1406. };
  1407. capture.StartRecording();
  1408. return true;
  1409. }
  1410. catch (Exception ex)
  1411. {
  1412. LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
  1413. return false;
  1414. }
  1415. }
  1416. #endregion
  1417. #endregion
  1418. }
  1419. }