C#(asp.net)上傳視頻轉換為flv格式並給視頻截圖代碼

來源:互聯網
上載者:User

在做視頻項目時一般是把視頻轉換為flv格式進行播放,還會在上傳的時候對視頻進行以顯示此視頻。為了方便大家,提供C#(asp.net)上傳視頻轉換為flv格式並給視頻代碼。

以下代碼是在添加視頻的作業碼:

                                string fileName = PublicMethod.GetFileName(_files[i].FileName);// GetFileName();
                                string upFileName = Server.MapPath(PublicMethod.upFile + fileName);
                                _files[i].SaveAs(upFileName);
                                string saveName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                                string playFile = Server.MapPath(PublicMethod.playFile + saveName);
                                string imgFile = Server.MapPath(PublicMethod.imgFile + saveName);
                                //System.IO.File.Copy(Server.MapPath(PublicMethod.playFile + "00000002.jpg"), Server.MapPath(PublicMethod.imgFile+"aa.jpg"));
                                PublicMethod pm = new PublicMethod();
                                string m_strExtension = PublicMethod.GetExtension(_files[i].FileName).ToLower();
                                if (m_strExtension == "flv")
                                {//直接拷貝到播放檔案夾下
                                    System.IO.File.Copy(upFileName, playFile + ".flv");
                                    pm.CatchImg(upFileName, imgFile);
                                }
                                string Extension = CheckExtension(m_strExtension);
                                if (Extension == "ffmpeg")
                                {
                                    pm.ChangeFilePhy(upFileName, playFile, imgFile);
                                    //pm.CatchImg(upFileName, imgFile);
                                }
                                else if (Extension == "mencoder")
                                {
                                    pm.MChangeFilePhy(upFileName, playFile, imgFile);
                                    pm.CatchImg(upFileName, imgFile);
                                }
                                else if (Extension == "error")
                                {
                                    Page.ClientScript.RegisterStartupScript(this.GetType(), "error", "<script language='javascript'>alert('不支援此視頻格式的上傳!');location.href('AddVideo.aspx');</script>");
                                }
                                string VideoUrl = PublicMethod.upFile + fileName;
                                string VideoFlvUrl = PublicMethod.playFile + saveName + ".flv";
                                string VideoImg = PublicMethod.imgFile + saveName + ".jpg";
                                ProductImage = VideoUrl + "," + VideoFlvUrl + "," + VideoImg;

PublicMethod類詳細代碼:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Company.COMM
{
    public class PublicMethod
    {
        public PublicMethod()
        {
            //
            // TODO: 在此處添加建構函式邏輯
            //
        }
        //檔案路徑
        public static string ffmpegtool ="http://www.cnblogs.com/ffmpeg/ffmpeg.exe";
        public static string mencodertool = "http://www.cnblogs.com/mencoder/mencoder.exe";
        public static string upFile = "http://www.cnblogs.com/UpFiles" + "/";
        public static string imgFile = "http://www.cnblogs.com/ImgFile" + "/";
        public static string playFile = "http://www.cnblogs.com/PlayFiles" + "/";
        //檔案圖片大小
        public static string sizeOfImg = "240x180";
        //檔案大小
        public static string widthOfFile = "400";
        public static string heightOfFile = "350";
        //   // //擷取檔案的名字
        public static string GetFileName(string fileName)
        {
            int i = fileName.LastIndexOf("\\") + 1;
            string Name = fileName.Substring(i);
            return Name;
        }
        //擷取副檔名
        public static string GetExtension(string fileName)
        {
            int i = fileName.LastIndexOf(".") + 1;
            string Name = fileName.Substring(i);
            return Name;
        }
        //
        #region //運行FFMpeg的視頻解碼,(這裡是絕對路徑)
        /// <summary>
        /// 轉換檔並儲存在指定檔案夾下面(這裡是絕對路徑)
        /// </summary>
        /// <param name="fileName">上傳視頻檔案的路徑(原檔案)</param>
        /// <param name="playFile">轉換後的檔案的路徑(網路播放檔案)</param>
        /// <param name="imgFile">從視頻檔案中抓取的圖片路徑</param>
        /// <returns>成功:返回圖片虛擬位址;   失敗:返回Null 字元串</returns>
        public string ChangeFilePhy(string fileName, string playFile, string imgFile)
        {
            //取得ffmpeg.exe的路徑,路徑配置在Web.Config中,如:<add   key="ffmpeg"   value="E:\aspx1\ffmpeg.exe"   />  
            string ffmpeg = HttpContext.Current.Server.MapPath(PublicMethod.ffmpegtool);
            if ((!System.IO.File.Exists(ffmpeg)) || (!System.IO.File.Exists(fileName)))
            {
                return "";
            }

            //獲得圖片和(.flv)檔案相對路徑/最後儲存到資料庫的路徑,如:/Web/User1/00001.jpg  

            string flv_file = System.IO.Path.ChangeExtension(playFile, ".flv");

            //的尺寸大小,配置在Web.Config中,如:<add   key="CatchFlvImgSize"   value="240x180"   />  
            string FlvImgSize = PublicMethod.sizeOfImg;

            System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);

            FilestartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            FilestartInfo.Arguments = " -i " + fileName + " -ab 56 -ar 22050 -b 500 -r 15 -s " + widthOfFile + "x" + heightOfFile + " " + flv_file;
            //ImgstartInfo.Arguments = "   -i   " + fileName + "   -y   -f   image2   -t   0.05   -s   " + FlvImgSize + "   " + flv_img;

            try
            {
                //轉換
                System.Diagnostics.Process.Start(FilestartInfo);
                //
                CatchImg(fileName, imgFile);
                //System.Diagnostics.Process.Start(ImgstartInfo);
            }
            catch
            {
                return "";
            }
            //
            return "";
        }
        //
        public string CatchImg(string fileName, string imgFile)
        {
            //
            string ffmpeg = HttpContext.Current.Server.MapPath(PublicMethod.ffmpegtool);
            //
            string flv_img = imgFile + ".jpg";
            //
            string FlvImgSize = PublicMethod.sizeOfImg;
            //
            System.Diagnostics.ProcessStartInfo ImgstartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            ImgstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            //
            ImgstartInfo.Arguments = "   -i   " + fileName + "  -y  -f  image2   -ss 2 -vframes 1  -s   " + FlvImgSize + "   " + flv_img;
            try
            {
                System.Diagnostics.Process.Start(ImgstartInfo);
            }
            catch
            {
                return "";
            }
            //
            if (System.IO.File.Exists(flv_img))
            {
                return flv_img;
            }

            return "";
        }
        #endregion
        //
        #region //運行FFMpeg的視頻解碼,(這裡是(虛擬)相對路徑)
        /// <summary>
        /// 轉換檔並儲存在指定檔案夾下面(這裡是相對路徑)
        /// </summary>
        /// <param name="fileName">上傳視頻檔案的路徑(原檔案)</param>
        /// <param name="playFile">轉換後的檔案的路徑(網路播放檔案)</param>
        /// <param name="imgFile">從視頻檔案中抓取的圖片路徑</param>
        /// <returns>成功:返回圖片虛擬位址;   失敗:返回Null 字元串</returns>
        public string ChangeFileVir(string fileName, string playFile, string imgFile)
        {
            //取得ffmpeg.exe的路徑,路徑配置在Web.Config中,如:<add   key="ffmpeg"   value="E:\aspx1\ffmpeg.exe"   />  
            string ffmpeg = HttpContext.Current.Server.MapPath(PublicMethod.ffmpegtool);
            if ((!System.IO.File.Exists(ffmpeg)) || (!System.IO.File.Exists(fileName)))
            {
                return "";
            }

            //獲得圖片和(.flv)檔案相對路徑/最後儲存到資料庫的路徑,如:/Web/User1/00001.jpg  
            string flv_img = System.IO.Path.ChangeExtension(HttpContext.Current.Server.MapPath(imgFile), ".jpg");
            string flv_file = System.IO.Path.ChangeExtension(HttpContext.Current.Server.MapPath(playFile), ".flv");

            //的尺寸大小,配置在Web.Config中,如:<add   key="CatchFlvImgSize"   value="240x180"   />  
            string FlvImgSize = PublicMethod.sizeOfImg;

            System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            System.Diagnostics.ProcessStartInfo ImgstartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);

            FilestartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            ImgstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            //此處組合成ffmpeg.exe檔案需要的參數即可,此處命令在ffmpeg   0.4.9調試通過
            //ffmpeg -i F:\01.wmv -ab 56 -ar 22050 -b 500 -r 15 -s 320x240 f:\test.flv
            FilestartInfo.Arguments = " -i " + fileName + " -ab 56 -ar 22050 -b 500 -r 15 -s " + widthOfFile + "x" + heightOfFile + " " + flv_file;
            ImgstartInfo.Arguments = "   -i   " + fileName + "   -y   -f   image2   -t   0.001   -s   " + FlvImgSize + "   " + flv_img;

            try
            {
                System.Diagnostics.Process.Start(FilestartInfo);
                System.Diagnostics.Process.Start(ImgstartInfo);
            }
            catch
            {
                return "";
            }

            /**/
            ///注意:圖片截取成功後,資料由記憶體緩衝寫到磁碟需要時間較長,大概在3,4秒甚至更長;  
            ///這兒需要延時後再檢測,我伺服器延時8秒,即如果超過8秒圖片仍不存在,認為失敗;  
            ///此處略去延時代碼.如有那位知道如何捕捉ffmpeg.exe失敗訊息,請告知,先謝過!  
            if (System.IO.File.Exists(flv_img))
            {
                return flv_img;
            }

            return "";
        }
        #endregion

        #region //運行mencoder的視頻解碼器轉換(這裡是(絕對路徑))
        public string MChangeFilePhy(string vFileName, string playFile, string imgFile)
        {
            string tool = HttpContext.Current.Server.MapPath(PublicMethod.mencodertool);
            //string mplaytool = HttpContext.Current.Server.MapPath(PublicMethod.ffmpegtool);

            if ((!System.IO.File.Exists(tool)) || (!System.IO.File.Exists(vFileName)))
            {
                return "";
            }

            string flv_file = System.IO.Path.ChangeExtension(playFile, ".flv");

            //的尺寸大小,配置在Web.Config中,如:<add   key="CatchFlvImgSize"   value="240x180"   />  
            string FlvImgSize = PublicMethod.sizeOfImg;

            System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(tool);

            FilestartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            FilestartInfo.Arguments = " " + vFileName + " -o " + flv_file + " -of lavf -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -oac

mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=200:mbd=2:mv0:trell:v4mv:cbp:last_pred=1:dia=-1:cmp=0:vb_strategy=1 -vf scale=" +

widthOfFile + ":" + heightOfFile + " -ofps 12 -srate 22050";
            try
            {
                System.Diagnostics.Process.Start(FilestartInfo);
                CatchImg(flv_file, imgFile);
            }
            catch
            {
                return "";
            }
            //
            return "";
        }
        #endregion

    }
}

把上述代碼直接進行複製既可實現C#(asp.net)上傳視頻轉換為flv格式並給視頻。如有疑問,可以官方技術社區(http://bbs.25yi.com)提問。來源:25億  。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.