12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316 |
- using AForge.Video.DirectShow;
-
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading;
-
- using VisioForge.Shared.NAudio.CoreAudioApi;
- using VisioForge.Shared.NAudio.Wave;
-
- namespace Common.system
- {
- /// <summary>
- /// ffmpeg帮助类
- /// 创建人:赵耀
- /// 创建时间::2020年8月22日
- /// 需要安装\SSCR\Setup Screen Capturer Recorder v0.12.10.exe
- /// 本地调试需要配置环境变量 将ffmpeg.exe位置配置到环境变量的path中
- /// </summary>
- public class FFMpeg
- {
- public Process myProcess = null;
-
- /// <summary>
- /// 是否输出录课录屏日志
- /// </summary>
- public bool OutputVideoLog = FileToolsCommon.GetConfigValue("OutputVideoLog") != "0";
- /// <summary>
- /// ffmpeg输出日志文件地址 每个文件2MB左右
- /// </summary>
- private string LogPath = "";
-
- /// <summary>
- /// 是否可以录制扬声器
- /// </summary>
- private bool IsRecordSpeaker = true;
-
- /// <summary>
- /// 是否可以录制麦克风
- /// </summary>
- private bool IsRecordMicrophone = true;
- /// <summary>
- /// 录制屏幕
- /// </summary>
- /// <param name="FilePath">文件存储路径</param>
- public bool StartRecordingVideo(string FilePath, Size size, out string ErrMessage)
- {
- while (myProcess != null)
- {
- Thread.Sleep(100);
- }
- ErrMessage = null;
- //路径
- string Path = FileToolsCommon.GetDirectoryName(FilePath);
- string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
- //文件保存路径
- string PathName = GetRSFilePathName(FilePath);
- Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in KillProcessArray)
- {
- KillProcess.Kill();
- }
- myProcess = new Process();
- LogPath = CreateffmpegLog();
- string MicrophoneName = null;
- #region 检测麦克风扬声器
- string AudioPath = FileToolsCommon.GetFileAbsolutePath("/temp/audio/");
- FileToolsCommon.CreateDirectory(AudioPath);
- string audioSpeakerPath = AudioPath + "adoS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";//FileToolsCommon.GetFileAbsolutePath("adoS.m");
- string audioMicrophonePath = AudioPath + "adoM" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";//FileToolsCommon.GetFileAbsolutePath("adoM.m");
- try
- {
- FileToolsCommon.DeleteFile(audioSpeakerPath);
- FileToolsCommon.DeleteFile(audioMicrophonePath);
- }
- catch (Exception)
- {
-
- }
- if (StartRecordSpeakerAudio(audioSpeakerPath))
- {
- IsRecordSpeaker = true;
- }
- else
- {
- //无法录制扬声器音频
- IsRecordSpeaker = false;
- }
- StopRecordAudio(2);
- Thread.Sleep(100);
- if (StartRecordAudio(audioMicrophonePath))
- {
- IsRecordMicrophone = true;
- }
- else
- {
- //无法录制麦克风
- IsRecordMicrophone = false;
- }
- StopRecordAudio(1);
- #endregion
- myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
- string SpeakerStr = "";
- string MicrophoneStr = "";
- if (IsRecordSpeaker)
- {
- SpeakerStr = "-f dshow -i audio=\"virtual-audio-capturer\" ";
- }
- if (IsRecordMicrophone)
- {
- MicrophoneName = GetMicrophoneName();
- if (!string.IsNullOrWhiteSpace(MicrophoneName))
- {
- MicrophoneStr = "-f dshow -i audio=\"" + MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 ";
- }
- }
- switch (Extension.ToUpper())
- {
- case ".MP4":
- 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;
- //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;
- //if (string.IsNullOrWhiteSpace(MicrophoneName))
- //{
- // 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的参数
- //}
- //else
- //{
- // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
- // 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的参数
- //}
- break;
- case ".AVI":
- case ".FLV":
- 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;
- //if (string.IsNullOrWhiteSpace(MicrophoneName))
- //{
- // 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的参数
- //}
- //else
- //{
- // myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
- // 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的参数
- //}
- break;
- default:
- 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;
- break;
- }
- if (OutputVideoLog)
- {
- LogHelper.WriteInfoLog("【录屏】:" + myProcess.StartInfo.Arguments);
- }
- FileToolsCommon.AppendText(LogPath, "【录屏】:" + myProcess.StartInfo.Arguments + "\r\n");
- myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
- myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
- myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
- myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
- myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
- try
- {
- myProcess.Start();
- myProcess.BeginErrorReadLine();
- }
- catch (Exception ex)
- {
- if (ex.Message.Contains("访问"))
- {
- ErrMessage = "访问被拒绝,请关闭杀毒软件或新任此软件后重试!";
- }
- else
- {
- ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
- }
- LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
- myProcess.Dispose();
- myProcess = null;
- return false;
- }
- return true;
- }
-
- /// <summary>
- /// 录制音频
- /// </summary>
- /// <param name="Mp3Path">MP3音频位置</param>
- public bool StartRecordingAudio(string Mp3Path, out string ErrMessage)
- {
- ErrMessage = null;
- while (myProcess != null)
- {
- Thread.Sleep(100);
- }
- //路径
- string Path = FileToolsCommon.GetDirectoryName(Mp3Path);
- //文件保存路径
- string PathName = GetFilePathName(Mp3Path);
- Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in KillProcessArray)
- {
- KillProcess.Kill();
- }
- string MicrophoneName = null;
- #region 检测麦克风扬声器
- string AudioPath = FileToolsCommon.GetFileAbsolutePath("/temp/audio/");
- FileToolsCommon.CreateDirectory(AudioPath);
- string audioSpeakerPath = AudioPath + "adoS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";
- string audioMicrophonePath = AudioPath + "adoM" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".m";
- try
- {
- FileToolsCommon.DeleteFile(audioSpeakerPath);
- FileToolsCommon.DeleteFile(audioMicrophonePath);
- }
- catch (Exception)
- {
-
- }
- if (StartRecordSpeakerAudio(audioSpeakerPath))
- {
- IsRecordSpeaker = true;
- }
- else
- {
- //无法录制扬声器音频
- IsRecordSpeaker = false;
- }
- StopRecordAudio(2);
- Thread.Sleep(100);
- if (StartRecordAudio(audioMicrophonePath))
- {
- IsRecordMicrophone = true;
- MicrophoneName = GetMicrophoneName();
- }
- else
- {
- //无法录制麦克风
- IsRecordMicrophone = false;
- }
- StopRecordAudio(1);
- if (!IsRecordSpeaker && !IsRecordMicrophone)
- {
- ErrMessage = "无法录制声音,请关闭杀毒软件,确保声卡和麦克风处于可用状态!";
- return false;
- }
- #endregion
- myProcess = new Process();
- LogPath = CreateffmpegLog();
- myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
- if (IsRecordSpeaker && IsRecordMicrophone)
- {
- myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" -f dshow -i audio=\"" +
- MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
- }
- else if (IsRecordSpeaker)
- {
- myProcess.StartInfo.Arguments = "-f dshow -i audio=\"virtual-audio-capturer\" " + PathName;
- }
- else if (IsRecordMicrophone)
- {
- //录制麦克风
- if (!string.IsNullOrWhiteSpace(MicrophoneName))
- {
- myProcess.StartInfo.Arguments = "-f dshow -i audio=\"" +
- MicrophoneName + "\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2 " + PathName;
- }
- }
- if (OutputVideoLog)
- {
- LogHelper.WriteInfoLog("【录音】:" + myProcess.StartInfo.Arguments);
- }
-
- FileToolsCommon.AppendText(LogPath, "【录音】:" + myProcess.StartInfo.Arguments + "\r\n");
- myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
- myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
- myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
- myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
- //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
- myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
- try
- {
- myProcess.Start(); //启动线程
- myProcess.BeginErrorReadLine(); //开始异步读取
- }
- catch (Exception ex)
- {
- if (ex.Message.Contains("访问"))
- {
- ErrMessage = "无法录制声音,访问被拒绝,请关闭杀毒软件或信任此软件后重试!";
- }
- else
- {
- ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
- }
- LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
- myProcess.Dispose();
- myProcess = null;
- return false;
- }
- return true;
- }
-
- /// <summary>
- /// 暂停录制
- /// </summary>
- public bool SuspendFFmpeg()
- {
- if (myProcess != null)
- {
- myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
- myProcess.Close();//关闭进程
- myProcess.Dispose();//释放资源
- }
- #region 进程是否已经释放
- bool IsRunning = true;
- while (IsRunning)
- {
- IsRunning = false;
- Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in ProcessArray)
- {
- IsRunning = true;
- Thread.Sleep(100);
- }
- }
- #endregion
- myProcess = null;
- return true;
- //myProcess.Kill();
- }
-
- /// <summary>
- /// 停止录制并合成文件
- /// </summary>
- /// <param name="FilePath">文件存储路径 必须与开始时的路径完全一致</param>
- public bool StopFFmpeg(string FilePath)
- {
- //文件完整路径
- if (myProcess != null)
- {
- myProcess.StandardInput.WriteLine("q");//在这个进程的控制台中模拟输入q,用于暂停录制
- myProcess.Close();//关闭进程
- myProcess.Dispose();//释放资源
- }
- #region 进程是否已经释放
- bool IsRunning = true;
- while (IsRunning)
- {
- IsRunning = false;
- Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in ProcessArray)
- {
- IsRunning = true;
- Thread.Sleep(100);
- }
- }
- #endregion
- myProcess = null;
- Thread t1 = new Thread(MergeVideoOrAudio);
- t1.Start(FilePath);
- return true;
- //文件合成
- }
-
- /// <summary>
- /// 图片音频合成视频
- /// </summary>
- /// <param name="ImageListPath">图片列表位置 命名为1.png 2.png</param>
- /// <param name="Mp3Path">MP3音频位置</param>
- /// <param name="VideoSavePath">视频保存位置</param>
- /// <param name="Frequency">每秒帧率</param>
- /// <param name="VideoWidth">视频宽度</param>
- /// <param name="VideoHeight">视频高度</param>
- public bool SynthesisVideo(string ImageListPath, string Mp3Path, string VideoSavePath, int Frequency, int VideoWidth, int VideoHeight, out string ErrMessage)
- {
- //new Thread(new ThreadStart(new Action(() =>
- //{
-
- //}))).Start();
- while (myProcess != null)
- {
- Thread.Sleep(100);
- }
- ErrMessage = null;
- string Extension = FileToolsCommon.GetIOExtension(VideoSavePath);//扩展名
- Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
- //Debug.WriteLine(KillProcessArray.Length.ToString());
- foreach (Process KillProcess in KillProcessArray)
- {
- KillProcess.Kill();
- }
- myProcess = new Process();
- try
- {
-
- LogPath = CreateffmpegLog();
- string mp3Str = "";
- #region 判断音频是否存在
- if (!string.IsNullOrWhiteSpace(Mp3Path))
- {
- if (FileToolsCommon.IsExistFile(Mp3Path))
- {
- mp3Str = "-i " + Mp3Path;
- }
- }
- #endregion
- myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
- switch (Extension.ToUpper())
- {
- case ".MP4":
- myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
- ImageListPath + @"%d.png " +
- mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
- VideoSavePath;
- break;
- case ".AVI":
- myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
- ImageListPath + @"%d.png " +
- mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f AVI " +
- VideoSavePath;
- break;
- case ".FLV":
- myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
- ImageListPath + @"%d.png " +
- mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -f FLV " +
- VideoSavePath;
- break;
- default:
- myProcess.StartInfo.Arguments = @"-y -r " + Frequency + " -i " +
- ImageListPath + @"%d.png " +
- mp3Str + @" -s " + VideoWidth + "x" + VideoHeight + " -vcodec mpeg4 " +
- VideoSavePath;
- break;
- }
- if (OutputVideoLog)
- {
- LogHelper.WriteInfoLog("【图片音频合成视频】:" + myProcess.StartInfo.Arguments);
- }
-
- FileToolsCommon.AppendText(LogPath, "【图片音频合成视频】:" + myProcess.StartInfo.Arguments + "\r\n");
- myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
- myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
- myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
- myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
- //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
- myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
- try
- {
- myProcess.Start(); //启动线程
- myProcess.BeginErrorReadLine(); //开始异步读取
- myProcess.WaitForExit(); //阻塞等待进程结束
- myProcess.Close(); //关闭进程
- }
- catch (Exception ex)
- {
- if (ex.Message.Contains("访问"))
- {
- ErrMessage = "访问被拒绝,请关闭杀毒软件或新任此软件后重试!";
- }
- else
- {
- ErrMessage = ex.Message + " 请关闭杀毒软件或信任此软件后重试!";
- }
- LogHelper.WriteErrLog("【录音】(StartRecordingAudio)" + ErrMessage, ex);
- myProcess.Dispose();
- myProcess = null;
- return false;
- }
- myProcess.Dispose(); //释放资源
- #region 进程是否已经释放
- bool IsRunning = true;
- while (IsRunning)
- {
- IsRunning = false;
- Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in ProcessArray)
- {
- IsRunning = true;
- Thread.Sleep(100);
- }
- }
- #endregion
- myProcess = null;
- //生成视频后删除图片和音频保存列表
- //FileToolsCommon.DeleteDirectory(ImageListPath);
- //FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(Mp3Path));
-
- Thread.Sleep(100);
- FileToolsCommon.DeleteDirectory(FileToolsCommon.GetDirectoryName(VideoSavePath) + "temp");
- return true;
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【视频合成】(SynthesisVideo)视频生成失败," + ex.Message, ex);
- ErrMessage = ex.Message;
- return false;
- }
- //Dispatcher.Invoke(() =>
- //{
- //});
- //// 允许不同线程间的调用
- //Control.CheckForIllegalCrossThreadCalls = false;
- }
-
- /// <summary>
- /// 视频音频合成
- /// </summary>
- /// <param name="FilePath">存储路径</param>
- public void MergeVideoOrAudio(object FilePathobj)
- {
- //new Thread(new ThreadStart(new Action(() =>
- //{
- //Dispatcher.Invoke(() =>
- //{
- //});
- //}))).Start();
-
- while (myProcess != null)
- {
- Thread.Sleep(100);
- }
- //路径
- string FilePath = (string)FilePathobj;
- string Path = FileToolsCommon.GetDirectoryName(FilePath);
- //扩展名
- string Extension = FileToolsCommon.GetIOExtension(FilePath);
- //Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
- //foreach (var KillProcess in KillProcessArray)
- //{
- // KillProcess.Kill();
- //}
- #region 判断文件是否存在
- if (Extension.ToUpper() == ".MP3")
- {
- if (!FileToolsCommon.IsExistFile(Path + "temp/filelist.d"))
- {
- return;
- }
- }
- else
- {
- if (!FileToolsCommon.IsExistFile(Path + "temprs/filelist.d"))
- {
- return;
- }
- }
- #endregion
- myProcess = new Process();
- LogPath = CreateffmpegLog();
- myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
- if (Extension.ToUpper() == ".MP3")
- {
- myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temp/filelist.d -c copy " + FilePath;
- }
- else
- {
-
- myProcess.StartInfo.Arguments = "-f concat -safe 0 -i " + Path + "temprs/filelist.d -c copy " + FilePath;
- }
- if (OutputVideoLog)
- {
- LogHelper.WriteInfoLog("【音视频合成】:" + myProcess.StartInfo.Arguments);
- }
-
- FileToolsCommon.AppendText(LogPath, "【音视频合成】:" + myProcess.StartInfo.Arguments + "\r\n");
- myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
- myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
- myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
- myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
- //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
- myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
- myProcess.Start(); //启动线程
- myProcess.BeginErrorReadLine(); //开始异步读取
- myProcess.WaitForExit(); //阻塞等待进程结束
- myProcess.Close(); //关闭进程
- myProcess.Dispose(); //释放资源
- #region 进程是否已经释放
- bool IsRunning = true;
- while (IsRunning)
- {
- IsRunning = false;
- Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in ProcessArray)
- {
- IsRunning = true;
- Thread.Sleep(100);
- }
- }
- #endregion
- myProcess = null;
- if (Extension.ToUpper() == ".MP3")
- {
- FileToolsCommon.DeleteDirectory(Path + "temp/");
- }
- else
- {
- FileToolsCommon.DeleteDirectory(Path + "temprs/");
- }
- }
-
- /// <summary>
- /// 获取文件完整路径 音频
- /// </summary>
- /// <param name="FilePath">文件路径</param>
- /// <returns></returns>
- private string GetFilePathName(string FilePath)
- {
- //路径
- string Path = FileToolsCommon.GetDirectoryName(FilePath);
- //Path.GetFileName(FilePath);//获取文件名
- string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
- string tempFilePath = Path + "temp/";
- //创建临时目录
- FileToolsCommon.CreateDirectory(tempFilePath);
- //创建记录文件
- if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
- {
- FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
- }
- int num = 1;
- string CompleteFilePath = tempFilePath + num + Extension;
- while (FileToolsCommon.IsExistFile(CompleteFilePath))
- {
- num++;
- CompleteFilePath = tempFilePath + num + Extension;
- }
- FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
- return CompleteFilePath;
- }
-
- /// <summary>
- /// 获取文件完整路径 录屏
- /// </summary>
- /// <param name="FilePath">文件路径</param>
- /// <returns></returns>
- private string GetRSFilePathName(string FilePath)
- {
- //路径
- string Path = FileToolsCommon.GetDirectoryName(FilePath);
- //Path.GetFileName(FilePath);//获取文件名
- string Extension = FileToolsCommon.GetIOExtension(FilePath);//扩展名
- string tempFilePath = Path + "temprs/";
- //创建临时目录
- FileToolsCommon.CreateDirectory(tempFilePath);
- //创建记录文件
- if (!FileToolsCommon.IsExistFile(tempFilePath + "filelist.d"))
- {
- FileToolsCommon.CreateFile(tempFilePath + "filelist.d");
- }
- int num = 1;
- string CompleteFilePath = tempFilePath + num + Extension;
- while (FileToolsCommon.IsExistFile(CompleteFilePath))
- {
- num++;
- CompleteFilePath = tempFilePath + num + Extension;
- }
- FileToolsCommon.AppendText(tempFilePath + "filelist.d", "file ./" + num + Extension + "\r\n");
- return CompleteFilePath;
- }
- /// <summary>
- /// 生成缩略图
- /// </summary>
- /// <param name="VideoPath">视频地址</param>
- /// <param name="ImagePath">图片地址</param>
- /// <param name="Width">图片大小</param>
- /// <param name="Height">图片大小</param>
- public bool GenerateThumbnails(string VideoPath, string ImagePath, int Width = 0, int Height = 0)
- {
- while (myProcess != null)
- {
- Thread.Sleep(100);
- }
- Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in KillProcessArray)
- {
- KillProcess.Kill();
- }
- string WHStr = "";
- if (Width > 0)
- {
- WHStr = " -s " + Width + "x" + Height;
- }
- try
- {
- myProcess = new Process();
- LogPath = CreateffmpegLog();
- myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
- //myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2 -s " + thubWidth + "*" + thubHeight + " -f image2 \"" + ImagePath + "\"";
- myProcess.StartInfo.Arguments = "-i \"" + VideoPath + "\" -ss 1 -vframes 1 -r 1 -ac 1 -ab 2" + WHStr + " -f image2 \"" + ImagePath + "\"";
-
- if (OutputVideoLog)
- {
- LogHelper.WriteInfoLog("【生成缩略图】:" + myProcess.StartInfo.Arguments);
- }
-
- FileToolsCommon.AppendText(LogPath, "【生成缩略图】:" + myProcess.StartInfo.Arguments + "\r\n");
- myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
- myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
- myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
- myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
- //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
- myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
- myProcess.Start(); //启动线程
- myProcess.BeginErrorReadLine(); //开始异步读取
- myProcess.WaitForExit(); //阻塞等待进程结束
- myProcess.Close(); //关闭进程
- myProcess.Dispose(); //释放资源
- #region 进程是否已经释放
- bool IsRunning = true;
- while (IsRunning)
- {
- IsRunning = false;
- Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in ProcessArray)
- {
- IsRunning = true;
- Thread.Sleep(100);
- }
- }
- #endregion
- myProcess = null;
- return true;
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【生成缩略图】(GenerateThumbnails)缩略图生成失败," + ex.Message, ex);
- return false;
- }
- }
- /// <summary>
- /// 视频转码
- /// </summary>
- /// <param name="VideoPathName">源视频</param>
- /// <param name="VideoSavePathName">目标视频存储路径</param>
- /// <param name="Width">宽</param>
- /// <param name="Height">高</param>
- /// <returns></returns>
- public bool VideoTranscode(string VideoPathName, string VideoSavePathName, int Width, int Height)
- {
- while (myProcess != null)
- {
- Thread.Sleep(100);
- }
- Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in KillProcessArray)
- {
- KillProcess.Kill();
- }
- try
- {
- myProcess = new Process();
- LogPath = CreateffmpegLog();
- myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
- myProcess.StartInfo.Arguments = "-i " + VideoPathName + " -acodec copy -vcodec libx264 -s " + Width + "*" + Height + " " + VideoSavePathName;
-
- if (OutputVideoLog)
- {
- LogHelper.WriteInfoLog("【视频转码】:" + myProcess.StartInfo.Arguments);
- }
-
- FileToolsCommon.AppendText(LogPath, "【视频转码】:" + myProcess.StartInfo.Arguments + "\r\n");
- myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
- myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
- myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
- myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
- //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
- myProcess.ErrorDataReceived += new DataReceivedEventHandler(Output);
- myProcess.Start(); //启动线程
- myProcess.BeginErrorReadLine(); //开始异步读取
- myProcess.WaitForExit(); //阻塞等待进程结束
- myProcess.Close(); //关闭进程
- myProcess.Dispose(); //释放资源
- #region 进程是否已经释放
- bool IsRunning = true;
- while (IsRunning)
- {
- IsRunning = false;
- Process[] ProcessArray = Process.GetProcessesByName("ffmpeg");
- foreach (Process KillProcess in ProcessArray)
- {
- IsRunning = true;
- Thread.Sleep(100);
- }
- }
- #endregion
- myProcess = null;
- Thread.Sleep(200);
- FileToolsCommon.DeleteFile(VideoPathName);
- return true;
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【视频转码】(VideoTranscode)视频转码失败," + ex.Message, ex);
- return false;
- }
- }
-
- /// <summary>
- /// 创建日志文件
- /// </summary>
- /// <returns></returns>
- private string CreateffmpegLog()
- {
- string LogFileName = DateTime.Now.ToString("yyyyMMdd");
- string LogFilePath = FileToolsCommon.GetFileAbsolutePath("/Log/FFMpegLog/");
- FileToolsCommon.CreateDirectory(LogFilePath);
- string LogName = LogFilePath + LogFileName + ".log";
- try
- {
- if (!FileToolsCommon.IsExistFile(LogName))
- {
- FileToolsCommon.CreateFile(LogName);
- FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
- "****************************************************************************************************\r\n");
- return LogName;
- }
- else
- {
- int num = 0;
- while (FileToolsCommon.GetFileSizeByMB(LogName) > 2)
- {
- num++;
- LogName = LogFilePath + LogFileName + "_" + num + ".log";
- FileToolsCommon.CreateFile(LogName);
- }
- FileToolsCommon.AppendText(LogName, "\r\n****************************************************************************************************" +
- "****************************************************************************************************\r\n");
- return LogName;
- }
- }
- catch (Exception)
- {
- return LogName;
- }
- }
-
- /// <summary>
- /// 输出结果
- /// </summary>
- /// <param name="sendProcess"></param>
- /// <param name="output"></param>
- private void Output(object sendProcess, DataReceivedEventArgs output)
- {
- if (!string.IsNullOrEmpty(output.Data))
- {
- FileToolsCommon.AppendText(LogPath, "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "】:");
- FileToolsCommon.AppendText(LogPath, output.Data + "\r\n");
- }
- }
- #region 麦克风声卡检测
- #region 获取麦克风
- private bool IsMicrophone = false;
-
- /// <summary>
- /// 使用FFmpeg获取的麦克风名
- /// </summary>
- private string MicrophoneNameInfo = "";
- /// <summary>
- /// 获取麦克风名称
- /// </summary>
- /// <returns></returns>
- public string GetMicrophoneName()
- {
- return GetAudioInDevices();
- //string FullName = GetInDeviceFull();
- //if(string.IsNullOrWhiteSpace(MicrophoneNameInfo))
- //{
- // return FullName;
- //}
- ////byte[] bufferASCII = Encoding.Default.GetBytes(MicrophoneNameInfo);
- ////string str = Encoding.UTF8.GetString(bufferASCII);
- ////str = str.Replace("?", " ");
- ////int num = str.Length;
- ////int num1 = FullName.Length;
- //if (FullName.Contains("(") || FullName.Contains("("))
- //{
- // string EName = FullName.Substring(FullName.IndexOf("(")+1);
- // if(string.IsNullOrEmpty(EName))
- // {
- // EName = FullName.Substring(FullName.IndexOf("(") + 1);
- // EName = EName.Substring(0, EName.LastIndexOf(")"));
- // }
- // else
- // {
- // //EName = EName.Substring(0, EName.LastIndexOf(")"));
- // }
- // if(MicrophoneNameInfo.Contains(EName))
- // {
- // return FullName;
- // }
- // else
- // {
- // return GetInDeviceName();
- // }
- //}
- //else
- //{
- // return FullName;
- //}
- }
- /// <summary>
- /// 使用FFmpeg获取设备名称--待定
- /// </summary>
- public void GetMToFFmpeg()
- {
- //return;
- new Thread(new ThreadStart(new Action(() =>
- {
- try
- {
-
- while (myProcess != null)
- {
- Thread.Sleep(100);
- }
- myProcess = new Process();
- LogPath = CreateffmpegLog();
- myProcess.StartInfo.FileName = FileToolsCommon.GetFileAbsolutePath(@"/ffmpeg/bin/ffmpeg.exe"); //ffmpeg.exe的绝对路径
- myProcess.StartInfo.Arguments = " -list_devices true -f dshow -i dummy";
- if (OutputVideoLog)
- {
- LogHelper.WriteInfoLog("【获取设备信息】:" + myProcess.StartInfo.Arguments);
- }
-
- FileToolsCommon.AppendText(LogPath, "【获取设备信息】:" + myProcess.StartInfo.Arguments + "\r\n");
- myProcess.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动
- myProcess.StartInfo.RedirectStandardError = true; //重定向标准错误输出
- myProcess.StartInfo.CreateNoWindow = true; //不显示程序窗口
- myProcess.StartInfo.RedirectStandardInput = true; //用于模拟该进程控制台的输入
- //外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
- myProcess.ErrorDataReceived += GetDevInfoData;
- myProcess.Start(); //启动线程
- myProcess.BeginErrorReadLine(); //开始异步读取
- myProcess.WaitForExit(); //阻塞等待进程结束
- myProcess.Close(); //关闭进程
- myProcess.Dispose(); //释放资源
- myProcess = null;
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【获取设备信息】(GetMToFFmpeg)信息获取失败:" + ex.Message, ex);
- }
-
- }))).Start();
- }
- /// <summary>
- /// 使用FFmpeg获取设备名称--待定
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void GetDevInfoData(object sender, DataReceivedEventArgs e)
- {
- if (!string.IsNullOrEmpty(e.Data))
- {
- if (IsMicrophone)
- {
- try
- {
- MicrophoneNameInfo = e.Data;
- MicrophoneNameInfo = MicrophoneNameInfo.Substring(MicrophoneNameInfo.IndexOf("]") + 1);
- MicrophoneNameInfo = MicrophoneNameInfo.Replace("\"", "");
- MicrophoneNameInfo = MicrophoneNameInfo.Trim();
- #region 测试
- //byte[] bufferASCII = Encoding.Default.GetBytes(MicrophoneNameInfo);
- //MicrophoneNameInfo = Encoding.UTF8.GetString(bufferASCII); // 统一使用UTF-8
- ////System.Text.Encoding GB2312 = System.Text.Encoding.GetEncoding("GB2312");
- ////byte[] gb = GB2312.GetBytes(MicrophoneNameInfo);
- ////MicrophoneNameInfo = Encoding.UTF8.GetString(gb);
- #endregion
- IsMicrophone = false;
- FileToolsCommon.AppendText(LogPath, e.Data);
- //FileToolsCommon.AppendText(LogPath, "\r\n***************************************************\r\n");
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【获取设备信息】(GetDevInfoData)信息获取失败:" + ex.Message, ex);
- }
- }
- else
- {
- if (e.Data.Contains("DirectShow audio devices"))
- {
- //FileToolsCommon.AppendText(LogPath, "\r\n***************************************************\r\n");
- IsMicrophone = true;
- }
- FileToolsCommon.AppendText(LogPath, e.Data);
- FileToolsCommon.AppendText(LogPath, "\r\n");
- }
- }
- }
-
- /// <summary>
- /// AForge获取麦克风
- /// </summary>
- /// <returns></returns>
- public static string GetAudioInDevices()
- {
- List<string> devicesList = new List<string>();
- try
- {
- FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.AudioInputDevice);
- foreach (FilterInfo device in videoDevices)
- {
- devicesList.Add(device.Name);
- }
- }
- catch (ApplicationException)
- {
- //Console.WriteLine("No local capture devices");
- }
-
- if (devicesList.Count > 1)
- {
- return devicesList[1];
- }
- else
- {
- return "";
- }
- }
- /// <summary>
- /// AForge获取麦克风列表
- /// </summary>
- /// <returns></returns>
- public static List<string> GetAudioInDevicesList()
- {
- List<string> devicesList = new List<string>();
- try
- {
- FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.AudioInputDevice);
- foreach (FilterInfo device in videoDevices)
- {
- devicesList.Add(device.Name);
- }
- }
- catch (ApplicationException)
- {
- //Console.WriteLine("No local capture devices");
- }
- return devicesList;
- }
- /// <summary>
- /// 获取声音输入设备名称 不完整
- /// </summary>
- /// <returns></returns>
- public static string GetInDeviceName()
- {
- List<WaveInCapabilities> devices = new List<WaveInCapabilities>();
- int waveInDevices = WaveIn.DeviceCount;
- for (int i = 0; i < waveInDevices; i++)
- {
- devices.Add(WaveIn.GetCapabilities(i));
- }
- List<string> devs = new List<string>();
- devs = devices.Select(item => item.ProductName).ToList();
-
- if (devs.Count > 0)
- {
- byte[] buffer = Encoding.UTF8.GetBytes(devs[0]);
- string MicrophoneName = Encoding.UTF8.GetString(buffer); // 统一使用UTF-8
- return MicrophoneName;
- }
- else
- {
- return "";
- }
- }
- /// <summary>
- /// 获取声音输入设备完整名称
- /// </summary>
- /// <returns></returns>
- public static string GetInDeviceFull()
- {
- List<string> devices = new List<string>();
- MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
- MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
- for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
- {
- WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
- foreach (MMDevice device in deviceCollection)
- {
- try
- {
- if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
- {
- devices.Add(device.FriendlyName);
- break;
- }
- }
- catch (Exception)
- {
- continue;
- }
- }
- }
- if (devices.Count > 0)
- {
- byte[] buffer = Encoding.UTF8.GetBytes(devices[0]);
- string MicrophoneName = Encoding.UTF8.GetString(buffer); // 统一使用UTF-8
- return MicrophoneName;
- }
- else
- {
- return "";
- }
- }
- /// <summary>
- /// 获取声音输入设备完整名称列表
- /// </summary>
- /// <returns></returns>
- public List<string> GetInDeviceListFull()
- {
- List<string> devices = new List<string>();
- MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
- MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
- for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
- {
- WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
- foreach (MMDevice device in deviceCollection)
- {
- try
- {
- if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
- {
- devices.Add(device.FriendlyName);
- break;
- }
- }
- catch (Exception)
- {
- continue;
- }
- }
- }
- return devices;
- }
- /// <summary>
- /// 获取麦克风---废弃
- /// </summary>
- private string GetMicrophone()
- {
- List<string> devs = new List<string>();
-
- MMDeviceEnumerator enumberator = new MMDeviceEnumerator();
- MMDeviceCollection deviceCollection = enumberator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
- for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
- {
- WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
- foreach (MMDevice device in deviceCollection)
- {
- try
- {
-
- if (device.FriendlyName.StartsWith(deviceInfo.ProductName))
- {
- devs.Add(device.FriendlyName);
- break;
- }
- }
- catch (Exception)
- {
-
- }
- }
- }
- if (devs.Count > 0)
- {
- return devs[0];
- }
- else
- {
- return "";
- }
- }
- #endregion
-
- #region 检测是否可用
- /// <summary>
- /// 录制麦克风的声音
- /// </summary>
- private WaveInEvent waveIn = null; //new WaveInEvent();
- /// <summary>
- /// 开始录制麦克风
- /// </summary>
- public bool StartRecordAudio(string audioFile)
- {
- try
- {
- waveIn = new WaveInEvent();
- //生成音频文件的对象
- WaveFileWriter writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
- //开始录音,写数据
- waveIn.DataAvailable += (s, a) =>
- {
- writer.Write(a.Buffer, 0, a.BytesRecorded);
- };
-
- //结束录音
- waveIn.RecordingStopped += (s, a) =>
- {
- writer.Dispose();
- writer = null;
- waveIn.Dispose();
- waveIn = null;
- try
- {
- FileToolsCommon.DeleteFile(audioFile);
- }
- catch (Exception)
- {
-
- }
- };
- waveIn.StartRecording();
- return true;
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
- return false;
- }
- }
-
- /// <summary>
- /// 结束录制音频
- /// </summary>
- /// <param name="type">1麦克风 2扬声器</param>
- public void StopRecordAudio(int type)
- {
- try
- {
- if (type == 1)
- {
- if (waveIn != null)
- {
- try
- {
- waveIn.StopRecording();
- }
- catch (Exception)
- {
- waveIn = null;
- }
- }
- }
- else if (type == 2)
- {
- if (capture != null)
- {
- try
- {
- capture.StopRecording();
- }
- catch (Exception)
- {
- capture = null;
- }
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
- }
- }
-
-
- /// <summary>
- /// 录制扬声器的声音
- /// </summary>
- private WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture();
-
- /// <summary>
- /// 开始录制扬声器
- /// </summary>
- public bool StartRecordSpeakerAudio(string audioFile)
- {
- try
- {
- capture = new WasapiLoopbackCapture();
- //生成音频文件的对象
- WaveFileWriter writer = new WaveFileWriter(audioFile, capture.WaveFormat);
- capture.DataAvailable += (s, a) =>
- {
- writer.Write(a.Buffer, 0, a.BytesRecorded);
- };
- //结束录音
- capture.RecordingStopped += (s, a) =>
- {
- writer.Dispose();
- writer = null;
- capture.Dispose();
- capture = null;
- try
- {
- FileToolsCommon.DeleteFile(audioFile);
- }
- catch (Exception)
- {
-
- }
- };
- capture.StartRecording();
- return true;
- }
- catch (Exception ex)
- {
- LogHelper.WriteErrLog("【麦克风】麦克风不可用:" + ex.Message, ex);
- return false;
- }
- }
- #endregion
- #endregion
- }
- }
|