ASP中將視頻文件轉(zhuǎn)換成.flv格式

2010-08-28 10:52:19來源:西部e網(wǎng)作者:

算一算,自從上次發(fā)表一篇asp.net中用VML畫數(shù)據(jù)統(tǒng)計圖的文章后差不多有一兩個月沒有來博客了,今天中秋,沒事做發(fā)現(xiàn)自己已經(jīng)很久沒有來博客園了.正好前幾天有小做一個視頻轉(zhuǎn)換的Demo,現(xiàn)在出現(xiàn)很的網(wǎng)上在線視頻其文件格式都是.FLV格式,那些視頻網(wǎng)站大概也有一個視頻轉(zhuǎn)換軟件,所我在也試著去做了一個demo拿出來和大家共享一下,由于自己的技術(shù)有限,做的不怎么樣,愿有高人看完給
在下指點一二.呵.... 費話不多說了,下面來分解一下這個Demo.

首先,我們部署一下文件夾.在工程的目錄下新建幾個文件夾如下圖:

\

 
中將視頻文件轉(zhuǎn)換成.flv格式UpFiles文件夾是要保存你上傳的文件,PlayFiles文件夾是用于你轉(zhuǎn)換后保存的文件(用于網(wǎng)上播放)

ImgFile文件夾是保存截取視頻文件的圖片,然后那兩個mencoder和ffmpeg文件夾是視頻轉(zhuǎn)換工具.此視頻轉(zhuǎn)換也
可叫做mencoder+ffmpeg視頻轉(zhuǎn)換.
首先,在配置文件中給這些文件夾進行路徑的配置.如下
<appSettings>
<!--工具文件夾-->
<add key="ffmpeg" value="ffmpeg/ffmpeg.exe"/>
<add key="mencoder" value="mencoder/mencoder.exe"/>
<add key="mplayer" value="mencoder/mplayer.exe"/>
<!--上傳文件的路徑-->
<add key="upfile" value="UpFiles"/>
<!--上專文件圖片路徑-->
<add key="imgfile" value="ImgFile"/>
<!--上傳文件圖片大小-->
<add key="CatchFlvImgSize" value="240x180"/>
<add key="widthSize" value="400"/>
<add key="heightSize" value="350"/>
<!--轉(zhuǎn)換后文件路徑-->
<add key="playfile" value="PlayFiles"/>
</appSettings>在上傳.ASPX頁面中

標題:<asp:TextBox ID="txtTitle" runat="server" Width="358px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtTitle"
ErrorMessage="標題不為空"></asp:RequiredFieldValidator>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" Width="339px" />
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="上傳視頻" Width="70px" />
文件類型<span style="color:Red;">(.asf .flv .avi .mpg .3gp .mov .wmv .rm .rmvb)</span>
<asp:RegularExpressionValidator ID="imagePathValidator" runat="server" ErrorMessage="文件類型不正確"
ValidationGroup="vgValidation" Display="Dynamic" ValidationExpression="^[a-zA-Z]:(\\.+)(.asf .flv .avi .mpg .3gp .mov .wmv .rm .rmvb)$"
ControlToValidate="FileUpload1">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="FileUpload1"
ErrorMessage="文件不為空"></asp:RequiredFieldValidator></div>
<div style=" height:0px; border-top:solid 1px red; font-size:0px;"></div>
<div>上傳列表.</div>程序工作的原理是:視頻先上傳上去,然后跟著就是開始轉(zhuǎn)換.
所以.在CS 文件中有
這里為了方便我是用sqlDatasource數(shù)據(jù)控件做數(shù)據(jù)的操作.
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;

public partial class _Default : System.Web.UI.Page
{
// 擴展名定義
string[] strArrFfmpeg = new string[] {"asf","avi","mpg","3gp","mov" };
string[] strArrMencoder = new string[] {"wmv","rm","rmvb" };
protected void Page_Load(object sender, EventArgs e)
{

}
//
protected void btnUpload_Click(object sender, EventArgs e)
{

string upFileName = "";
if (this.FileUpload1.HasFile)
{
string fileName = PublicMethod.GetFileName(this.FileUpload1.FileName);// GetFileName();
if ((string)Session["file"] == fileName)
{
return;
}
upFileName = Server.MapPath(PublicMethod.upFile + fileName);
this.FileUpload1.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(this.FileUpload1.PostedFile.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);
}
else if (Extension == "mencoder")
{
pm.MChangeFilePhy(upFileName, playFile, imgFile);
}
InsertData(this.txtTitle.Text, fileName,saveName);
Session["file"] = fileName;
}

}

//
private string CheckExtension(string extension)
{
string m_strReturn = "";
foreach (string var in this.strArrFfmpeg)
{
if (var == extension)
{
m_strReturn = "ffmpeg"; break;
}
}
if (m_strReturn == "")
{
foreach (string var in strArrMencoder)
{
if (var == extension)
{
m_strReturn = "mencoder"; break;
}
}
}
return m_strReturn;
}
#region 插入數(shù)據(jù)到數(shù)據(jù)庫中
private void InsertData(string MediaName,string fileName,string saveName)
{
//string name=fileName.Substring(0, fileName.LastIndexOf('.'));
string imgName = saveName + ".jpg";//圖片文件名;
string playName = saveName + ".flv";
string sqlstr = "insert into Media(FMediaName,FMediaUpPath,FMediaPlayPath,FMediaImgPath) values(@MName,@MUppath,@MPlaypath,@MImgpath)";
//string constr = ConfigurationManager.ConnectionStrings["sqlcon"].ToString();
SqlDataSource1.InsertCommand = sqlstr;
SqlDataSource1.InsertCommandType = SqlDataSourceCommandType.Text;// CommandType.Text;
SqlDataSource1.InsertParameters.Add("MName",MediaName);
SqlDataSource1.InsertParameters.Add("MUppath",PublicMethod.upFile+fileName);
SqlDataSource1.InsertParameters.Add("MPlaypath",PublicMethod.playFile+playName);
SqlDataSource1.InsertParameters.Add("MImgpath",PublicMethod.imgFile+imgName);
SqlDataSource1.Insert();
}
#endregion

}
PublicMethod類如下:
在這個類里面主要是做文件轉(zhuǎn)換和保存,在轉(zhuǎn)換文件的時候CPU的利用率可以達100%.

它的主要原理是另起一個進程在轉(zhuǎn)換的時候你會發(fā)現(xiàn)你的進程里多了一個.
using System;
using System.Configuration;

/// <summary>
/// Summary description for PublicMethod
/// </summary>
public class PublicMethod:System.Web.UI.Page
{
public PublicMethod()
{

}
//文件路徑
public static string ffmpegtool = ConfigurationManager.AppSettings["ffmpeg"];
public static string mencodertool = ConfigurationManager.AppSettings["mencoder"];
public static string mplayertool = ConfigurationManager.AppSettings["mplayer"];
public static string upFile = ConfigurationManager.AppSettings["upfile"] + "/";
public static string imgFile = ConfigurationManager.AppSettings["imgfile"] + "/";
public static string playFile = ConfigurationManager.AppSettings["playfile"] + "/";
//文件圖片大小
public static string sizeOfImg = ConfigurationManager.AppSettings["CatchFlvImgSize"];
//文件大小
public static string widthOfFile = ConfigurationManager.AppSettings["widthSize"];
public static string heightOfFile = ConfigurationManager.AppSettings["heightSize"];
// // //獲取文件的名字
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>
/// 轉(zhuǎn)換文件并保存在指定文件夾下面(這里是絕對路徑)
/// </summary>
/// <param name="fileName">上傳視頻文件的路徑(原文件)</param>
/// <param name="playFile">轉(zhuǎn)換后的文件的路徑(網(wǎng)絡(luò)播放文件)</param>
/// <param name="imgFile">從視頻文件中抓取的圖片路徑</param>
/// <returns>成功:返回圖片虛擬地址; 失敗:返回空字符串</returns>
public string ChangeFilePhy(string fileName, string playFile, string imgFile)
{
//取得ffmpeg.exe的路徑,路徑配置在Web.Config中,如:<add key="ffmpeg" value="E:\51aspx\ffmpeg.exe" />
string ffmpeg = Server.MapPath(PublicMethod.ffmpegtool);
if ((!System.IO.File.Exists(ffmpeg))    (!System.IO.File.Exists(fileName)))
{
return "";
}

//獲得圖片和(.flv)文件相對路徑/最后存儲到數(shù)據(jù)庫的路徑,如:/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
{
//轉(zhuǎn)換
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 = 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>
/// 轉(zhuǎn)換文件并保存在指定文件夾下面(這里是相對路徑)
/// </summary>
/// <param name="fileName">上傳視頻文件的路徑(原文件)</param>
/// <param name="playFile">轉(zhuǎn)換后的文件的路徑(網(wǎng)絡(luò)播放文件)</param>
/// <param name="imgFile">從視頻文件中抓取的圖片路徑</param>
/// <returns>成功:返回圖片虛擬地址; 失敗:返回空字符串</returns>
public string ChangeFileVir(string fileName, string playFile, string imgFile)
{
//取得ffmpeg.exe的路徑,路徑配置在Web.Config中,如:<add key="ffmpeg" value="E:\51aspx\ffmpeg.exe" />
string ffmpeg = Server.MapPath(PublicMethod.ffmpegtool);
if ((!System.IO.File.Exists(ffmpeg))    (!System.IO.File.Exists(fileName)))
{
return "";
}

//獲得圖片和(.flv)文件相對路徑/最后存儲到數(shù)據(jù)庫的路徑,如:/Web/User1/00001.jpg
string flv_img = System.IO.Path.ChangeExtension(Server.MapPath(imgFile), ".jpg");
string flv_file = System.IO.Path.ChangeExtension(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文件需要的參數(shù)即可,此處命令在ffmpeg 0.4.9調(diào)試通過
//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 "";
}

/**/
///注意:圖片截取成功后,數(shù)據(jù)由內(nèi)存緩存寫到磁盤需要時間較長,大概在3,4秒甚至更長;
///這兒需要延時后再檢測,我服務(wù)器延時8秒,即如果超過8秒圖片仍不存在,認為截圖失敗;
///此處略去延時代碼.如有那位知道如何捕捉ffmpeg.exe截圖失敗消息,請告知,先謝過!
if (System.IO.File.Exists(flv_img))
{
return flv_img;
}

return "";
}
#endregion

#region //運行mencoder的視頻解碼器轉(zhuǎn)換(這里是(絕對路徑))
public string MChangeFilePhy(string vFileName, string playFile, string imgFile)
{
string tool = Server.MapPath(PublicMethod.mencodertool);
//string mplaytool = 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
}

全文的主要內(nèi)容就在這里了。
關(guān)鍵詞:ASP

贊助商鏈接: