本文記錄使用 ASP.NET 搭配 Adobe Flash Media Server (FMS) 開發視頻網站的完整流程,涵蓋伺服器安裝、Flash 採集控件製作、上傳邏輯、FLV 流式傳輸處理等關鍵環節。
IHttpHandler 處理 FLV 檔案的範圍請求與標頭輸出,支援拖曳定位播放。public class FLVStreaming : IHttpHandler
{
private static readonly byte[] _flvheader = HexToByte("464C5601010000000900000009");
public void ProcessRequest(HttpContext context)
{
try
{
string filename = Path.GetFileName(context.Request.FilePath);
using (FileStream fs = new FileStream(context.Server.MapPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read))
{
string qs = context.Request.Params["start"];
int pos = string.IsNullOrEmpty(qs) ? 0 : Convert.ToInt32(qs);
int length = string.IsNullOrEmpty(qs) ? (int)fs.Length : (int)(fs.Length - pos) + _flvheader.Length;
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.AppendHeader("Content-Type", "video/x-flv");
context.Response.AppendHeader("Content-Length", length.ToString());
if (pos > 0)
{
context.Response.OutputStream.Write(_flvheader, 0, _flvheader.Length);
fs.Position = pos;
}
const int buffersize = 16384;
byte[] buffer = new byte[buffersize];
int count = fs.Read(buffer, 0, buffersize);
while (count > 0 && context.Response.IsClientConnected)
{
context.Response.OutputStream.Write(buffer, 0, count);
count = fs.Read(buffer, 0, buffersize);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
private static byte[] HexToByte(string hexString) { /* 實作略 */ }
}
start 參數支援 HTTP Range 請求,實現視頻拖曳跳轉。IsClientConnected 避免客戶端斷線後的資源浪費。Public 快取與 Last-Modified,優化重複播放效能。完成 web.config 處理器映射配置後,即可在頁面嵌入 Flash 播放器(如 JW Player、Flowplayer)指向 .flv 路徑測試。作者表示播放速度表現優異,提供了 ASP.NET 開發視頻網站的可行架構參考。