C# 利用ffmpeg进行本地文件转码

来源:互联网 发布:淘宝店铺可以注销吗 编辑:程序博客网 时间:2024/06/06 00:22

        前几天公司前端需要一个通过ftp上传文件到服务器的接口,故此并且要求对上传的文件进行转码,如:所有的视频上传到服务器上要求存储为mp4格式,音频要求在服务器上存储为mp3格式,图片为jpg格式。现在贴一下本地文件转码存储在本地的代码,这里用到的是ffmpeg.exe工具,特此说明一下,一些人说的改后缀的方法并不正确,还是要以科学为准啊。

        首先分享一下ffmpeg.exe,先下载到本地,链接: https://pan.baidu.com/s/1hrBOHl6   密码: ufcq 

        下载的ffmpeg.exe和需要转换的文件不要放在C盘,有时候读取不到,你们懂的~

        我将整个方法写在一个类里面,然后代码如下:

        

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;
namespace FormatFactory{   public class FileConvertTargetFil    {        /// <summary>        /// 文件格式转换        /// </summary>        /// <param name="applicationPath">ffmeg.exe文件路径</param>        /// <param name="fileName">文件的路径(带文件名)</param>        /// <param name="targetFilName">转换后文件路径(带文件名)</param>
            /// <param name="type">文件类型</param>       public void ConvertToAmr(string applicationPath, string fileName, string targetFilName, int type)       {           string c = "";           if (type == 1)//图片           {               c = applicationPath + @"\ffmpeg.exe -i " + fileName + " " + targetFilName + "";//定义ffmpeg命令           }           else if (type == 0)//视频           {               c = applicationPath + @"\ffmpeg.exe -i " + fileName + " -ab 56 -ar 22050 -b 1500 -r 29.97 -s 1280x720 " + targetFilName + "";           }           else if(type == 2)//音频           {            c = applicationPath + @"\ffmpeg.exe -i " + fileName + " " + targetFilName + "";           }           Cmd(c);       }        /// <summary>        /// 执行Cmd命令        /// </summary>        public void Cmd(string c)        {            try            {                System.Diagnostics.Process process = new System.Diagnostics.Process();//通过Process打开cmd来运行ffmpeg                process.StartInfo.FileName = "cmd.exe";                process.StartInfo.UseShellExecute = false;                process.StartInfo.CreateNoWindow = true;                process.StartInfo.RedirectStandardOutput = true;                process.StartInfo.RedirectStandardInput = true;                process.Start();                process.StandardInput.WriteLine(c);                process.StandardInput.AutoFlush = true;                process.StandardInput.WriteLine("exit");                StreamReader reader = process.StandardOutput;//截取输出流                           process.WaitForExit();            }            catch            { }        }        /// <summary>        /// 获取文件的byte[]        /// </summary>        /// <param name="fileName"></param>        /// <returns></returns>        public byte[] GetFileByte(string fileName)        {            FileStream pFileStream = null;            byte[] pReadByte = new byte[0];            try            {                pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);                BinaryReader r = new BinaryReader(pFileStream);                r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件                pReadByte = r.ReadBytes((int)r.BaseStream.Length);                return pReadByte;            }            catch            {                return pReadByte;            }            finally            {                if (pFileStream != null)                    pFileStream.Close();            }        }        /// <summary>        /// 将文件的byte[]生成文件        /// </summary>        /// <param name="pReadByte"></param>        /// <param name="fileName"></param>        /// <returns></returns>        public bool writeFile(byte[] pReadByte, string fileName)        {            FileStream pFileStream = null;            try            {                pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);                pFileStream.Write(pReadByte, 0, pReadByte.Length);            }            catch            {                return false;            }            finally            {                if (pFileStream != null)                    pFileStream.Close();                      }            return true;        }    }}
       这里说明一下ffmpeg,它相当于一个转换工具,因为C#并没有内置的转换文件格式的方法,所有需要借用第三方,核心就是ffmpeg命令,具体可以参考如下:

基本选项:-formats输出所有可用格式-f fmt指定格式(音频或视频格式)-i filename指定输入文件名,在linux下当然也能指定:0.0(屏幕录制)或摄像头-y覆盖已有文件-t duration记录时长为t-fs limit_size设置文件大小上限-ss time_off从指定的时间(s)开始, [-]hh:mm:ss[.xxx]的格式也支持-itsoffset time_off设置时间偏移(s),该选项影响所有后面的输入文件。该偏移被加到输入文件的时戳,定义一个正偏移意味着相应的流被延迟了 offset
秒。 [-]hh:mm:ss[.xxx]的格式也支持-title string标题-timestamp time时间戳-author string作者-copyright string版权信息-comment string评论-album stringalbum名-v verbose与log相关的-target type设置目标文件类型("vcd", "svcd", "dvd", "dv", "dv50", "pal-vcd", "ntsc-svcd", ...)-dframes number设置要记录的帧数视频选项:-b指定比特率(bits/s),似乎ffmpeg是自动VBR的,指定了就大概是平均比特率-bitexact使用标准比特率-vb指定视频比特率(bits/s)-vframes number设置转换多少桢(frame)的视频-r rate帧速率(fps) (可以改,确认非标准桢率会导致音画不同步,所以只能设定为15或者29.97)-s size指定分辨率 (320x240)-aspect aspect设置视频长宽比(4:3, 16:9 or 1.3333, 1.7777)-croptop size设置顶部切除尺寸(in pixels)-cropbottom size设置底部切除尺寸(in pixels)-cropleft size设置左切除尺寸 (in pixels)-cropright size设置右切除尺寸 (in pixels)-padtop size设置顶部补齐尺寸(in pixels)-padbottom size底补齐(in pixels)-padleft size左补齐(in pixels)-padright size右补齐(in pixels)-padcolor color补齐带颜色(000000-FFFFFF)-vn取消视频-vcodec codec强制使用codec编解码方式('copy' to copy stream)-sameq使用同样视频质量作为源(VBR)-pass n选择处理遍数(1或者2)。两遍编码非常有用。第一遍生成统计信息,第二遍生成精确的请求的码率-passlogfile file选择两遍的纪录文件名为file-newvideo在现在的视频流后面加入新的视频流 高级视频选项-pix_fmt formatset pixel format, 'list' as argument shows all the pixel formats supported-intra仅适用帧内编码-qscale q以<数值>质量为基础的VBR,取值0.01-255,约小质量越好-loop_input设置输入流的循环数(目前只对图像有效)-loop_output设置输出视频的循环数,比如输出gif时设为0表示无限循环-g int设置图像组大小-cutoff int设置截止频率-qmin int设定最小质量,与-qmax(设定最大质量)共用,比如-qmin 10 -qmax 31-qmax int设定最大质量-qdiff int量化标度间最大偏差 (VBR)-bf int使用frames B 帧,支持mpeg1,mpeg2,mpeg4音频选项:-ab设置比特率(单位:bit/s,也许老版是kb/s)前面-ac设为立体声时要以一半比特率来设置,比如192kbps的就设成96,转换 默认比特率都较小,要听到
较高品质声音的话建议设到160kbps(80)以上。-aframes number设置转换多少桢(frame)的音频-aq quality设置音频质量 (指定编码)-ar rate设置音频采样率 (单位:Hz),PSP只认24000-ac channels设置声道数,1就是单声道,2就是立体声,转换单声道的TVrip可以用1(节省一半容量),高品质的DVDrip就可以用2-an取消音频-acodec codec指定音频编码('copy' to copy stream)-vol volume设置录制音量大小(默认为256) <百分比> ,某些DVDrip的AC3轨音量极小,转换时可以用这个提高音量,比如200就是原来的2倍-newaudio在现在的音频流后面加入新的音频流字幕选项:-sn取消字幕-scodec codec设置字幕编码('copy' to copy stream)-newsubtitle在当前字幕后新增-slang code设置字幕所用的ISO 639编码(3个字母)Audio/Video 抓取选项:-vc channel设置视频捕获通道(只对DV1394)-tvstd standard设置电视标准 NTSC PAL(SECAM)        要得到一个高画质音质低容量的MP4的话,首先画面最好不要用固定比特率,而用VBR参数让程序自己去判断,而音质参数可以在原来的基础上提升一点,
听起来要舒服很多,也不会太大(看情况调整 )         转换为flv:     ffmpeg -i test.mp3 -ab 56 -ar 22050 -b 500 -r 15 -s 320x240 test.flv     ffmpeg -i test.wmv -ab 56 -ar 22050 -b 500 -r 15 -s 320x240 test.flv         转换文件格式的同时抓缩微图:     ffmpeg -i "test.avi" -y -f image2 -ss 8 -t 0.001 -s 350x240 'test.jpg'         对已有flv抓图:     ffmpeg -i "test.flv" -y -f image2 -ss 8 -t 0.001 -s 350x240 'test.jpg'         转换为3gp:    ffmpeg -y -i test.mpeg -bitexact -vcodec h263 -b 128 -r 15 -s 176x144 -acodec aac -ac 2 -ar 22500 -ab 24 -f 3gp test.3gp     ffmpeg -y -i test.mpeg -ac 1 -acodec amr_nb -ar 8000 -s 176x144 -b 128 -r 15 test.3gp         例:ffmpeg -y -i "test.avi" -title "Test" -vcodec xvid -s 368x208 -r 29.97 - b 1500 -acodec aac -ac 2 -ar 24000 -ab 128 -vol 200 -f 
psp -muxvb 768 "test.***"     # 参数解释:     -y(覆盖输出文件,即如果1.***文件已经存在的话,不经提示就覆盖掉了)     -i "1.avi"(输入文件是和ffmpeg在同一目录下的1.avi文件,可以自己加路径,改名字)     -title "Test"(在PSP中显示的影片的标题)     -vcodec xvid(使用XVID编码压缩视频,不能改的)     -s 368x208(输出的分辨率为368x208,注意片源一定要是16:9的不然会变形)     -r 29.97(帧数,一般就用这个吧)     -b 1500(视频数据流量,用-b xxxx的指令则使用固定码率,数字随便改,1500以上没效果;还可以用动态码率如:-qscale 4和-qscale 6,4的质量比6高)     -acodec aac(音频编码用AAC)     -ac 2(声道数1或2)     -ar 24000(声音的采样频率,好像PSP只能支持24000Hz)     -ab 128(音频数据流量,一般选择32、64、96、128)     -vol 200(200%的音量,自己改)     -f psp(输出psp专用格式)     -muxvb 768(好像是给PSP机器识别的码率,一般选择384、512和768,我改成1500,PSP就说文件损坏了)     "test.***"(输出文件名,也可以加路径改文件名)

结果如下:



原创粉丝点击