使用ASP.NET进行渐进式Mp4流式传输

时间:2012-03-16 01:50:19

标签: c# asp.net streaming mp4 http-streaming

我在使用asp.net脚本从任何部分或部分播放mp4视频时遇到问题。当您从开始流式传输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();
}

我认为问题出现在以下行中,如果我删除它,视频仍然可以播放,但从一开始        if(位置> 0)        {            fs.Position = position;        } 如果搜索位置>,则可能存在像flv流中一样用于跟踪搜索位置的起始mp4标题,因为哪个流不能被识别。 0

任何人都可以帮助我。

问候。

1 个答案:

答案 0 :(得分:0)

You set the Content-Length to the file length but then only send part of the file.

Also I don't think you can just divide the video like that, I think you have to set the file position to the beginning of an I-frame, this would mean somehow parsing the mp4 file and finding the nearest I-frame to the time you want and set the file position to that byte then start streaming from there.