星火直播PC
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FFMpeg.cs 61KB

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