2012-03-16 38 views
0

我使用asp.net腳本從任何部分或節點傳輸mp4視頻時遇到問題。當您從開始播放mp4視頻時,腳本運行良好,但如果您想選擇任何起點,則無法流式播放。我使用使用ASP.NET的漸進Mp4流式傳輸

if (filename.EndsWith(".mp4") && filename.Length > 2) 
{ 
    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); 
    // Sample logic to calculate approx length based on starting time. 
    if (context.Request.Params["starttime"] != null && context.Request.Params["d"] != null) 
    { 
     double total_duration = Convert.ToDouble(context.Request.Params["d"]); 
     double startduration = Convert.ToDouble(context.Request.Params["starttime"]); 
     double length_sec = (double)fs.Length/total_duration; // total length per second 
     seekpos = (long)(length_sec * startduration); 
    } 
    if (seekpos==0) 
    { 
     position = 0; 
     length = Convert.ToInt32(fs.Length); 
    } 
    else 
    { 
     position = Convert.ToInt32(seekpos); 
     length = Convert.ToInt32(fs.Length - position); 
    } 
    // Add HTTP header stuff: cache, content type and length   
    context.Response.Cache.SetCacheability(HttpCacheability.Public); 
    context.Response.Cache.SetLastModified(DateTime.Now); 
    context.Response.AppendHeader("Content-Type", "video/mp4"); 
    context.Response.AppendHeader("Content-Length", length.ToString()); 
    if (position > 0) 
    { 
     fs.Position = position; 
    } 
    // Read buffer and write stream to the response stream 
    const int buffersize = 16384; 
    byte[] buffer = new byte[buffersize]; 

    int count = fs.Read(buffer, 0, buffersize); 
    while (count > 0) 
    { 
     if (context.Response.IsClientConnected) 
     { 
      context.Response.OutputStream.Write(buffer,0, count); 
      context.Response.Flush(); 
      count = fs.Read(buffer, 0, buffersize); 
     } 
     else 
     { 
      count = -1; 
     } 
    } 
    fs.Close(); 
} 

示例腳本,我認爲問題出在下面的行,如果我將其刪除,視頻仍然可以播放,但是從開始 如果(倉位> 0) { FS。位置=位置; } 有可能是開始mp4頭像flv流中使用跟蹤尋找位置,由於無法識別哪個流,如果查找位置> 0

任何人都可以幫助我。

問候。

+1

也許你應該考慮一些玩家(silverlight或閃光燈),因爲在FileStream中設置位置僅適用於文本文件。在mp4上工作的機會非常小。 – mslliviu 2012-03-16 07:52:35

+0

問題是,例如當用戶點擊像jwplayer這樣的flash播放器時,它會發送starttime到流式腳本,但是流式腳本無法從mp4發出請求的位置發送內容,它在flash flv情況下工作。它可以在實現http://h264.code-shop.com/trac/wiki/Mod-H264-Streaming-Internet-Information-Services-IIS7-Version2時起作用,但是如果直接通過http腳本進行工作,它會很容易。 – irfanmcsd 2012-03-16 16:22:29

回答

0

您將Content-Length設置爲文件長度,但只發送部分文件。

另外我不認爲你可以像這樣分割視頻,我認爲你必須將文件位置設置爲I幀的開頭,這將意味着以某種方式解析mp4文件並找到最近的I - 幀到你想要的時間,並將文件位置設置爲該字節,然後從那裏開始流式傳輸。