偶然收到一份需求,需要将wmv的视频文件,转换成MP4格式,以方便公众号、自媒体等推送后,在线点击播放。
实现思路:下载了格式工厂,提供的方法可满足业务需求,可无损将wmv文件进行转换。出于业务化的考虑,进行了一点点尝试。如果MP4文件的码流格式无要求,那么,你可以按我下面的步骤来实现。
外部应用:
说明:mplayer.exe 主要提供桌面端应用视频的播放功能;
mencoder.exe是Mplayer自带的编码工具(Mplayer是Linux下的播放器,开源,支持几乎所有视频格式的播放,有windows和Mac版本)
ffmpeg.exe FLV视频转换器,可以轻易地实现FLV向其它格式avi、asf、 mpeg的转换或者将其它格式转换为flv ,我主要也是用它来实现转换。
不多说,show my code
1.创建一个ProcessStartInfo,去调用ffmpeg.exe
private static void Dowork(FileInfo fileinfo) { logger.InfoFormat("start deal file {0}",fileinfo.Name); var ffmpegPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Extention", "ffmpeg.exe"); var parameters = BuildCommon(fileinfo); var oInfo = new ProcessStartInfo(ffmpegPath,parameters); oInfo.UseShellExecute = false; oInfo.CreateNoWindow = true; oInfo.RedirectStandardOutput = true; oInfo.RedirectStandardError = true; oInfo.RedirectStandardInput = true; try { //调用ffmpeg开始处理命令 var proc = Process.Start(oInfo); proc.StartInfo = oInfo; proc.ErrorDataReceived+=new DataReceivedEventHandler(OnReceive); proc.OutputDataReceived += new DataReceivedEventHandler(OnReceive); proc.Start(); proc.BeginErrorReadLine(); proc.WaitForExit(); //转换成string //关闭处理程序 proc.Close(); proc.Dispose(); } catch (Exception ex) { logger.Error(ex); } finally { } logger.InfoFormat("finish deal file {0}", fileinfo.Name); }
2.获取原视频 相关参数,包括宽高、fps、音频码率、音频采样率等等信息
private static VideoFile GetMovieInfo(string file) { var ffmpegPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Extention", "ffmpeg.exe"); var enc=new VideoEncoder.Encoder(); enc.FFmpegPath = ffmpegPath; VideoFile videoFile = new VideoFile(file); enc.GetVideoInfo(videoFile); return videoFile; }
3.构建转换参数 参数定义源码中有详细解释
private static string BuildCommon(FileInfo file) { var parameters = "-i {1} -c:v libx264 -strict -2 {0} {2}"; var videoinfo=GetMovieInfo(file.FullName); var commond = ""; if (!string.IsNullOrEmpty(_scale)) { commond += string.Format(" -s {0}", _scale); } else { commond += string.Format(" -s {0}x{1}", videoinfo.Width,videoinfo.Height); } if (!string.IsNullOrEmpty(_fps)) { commond += string.Format(" -r {0}", _fps); } else { commond += string.Format(" -r {0}", videoinfo.Fps); } if (!string.IsNullOrEmpty(_datarate)) { commond += string.Format(" -b {0}", _datarate); } else { commond += " -qscale 4"; } if (!string.IsNullOrEmpty(_bitrate)) { commond += string.Format(" -ab {0}", _bitrate); } else { commond += string.Format(" -ab {0}k", videoinfo.AudioRate); } if (!string.IsNullOrEmpty(_freq)) { commond += string.Format(" -ar {0}", _freq); } else { commond += string.Format(" -ar {0}k", videoinfo.AudioFreq); } return string.Format(parameters, commond, file.FullName, file.FullName.Replace(".wmv", ".mp4")); }
总结:FFMPEG.EXE非常强大,市场是主流的转码工具,视频合成、剪切工具都是基于它为底层进行的二次开发,可根据自己的实际需要,来进行研究。
源代码