0

我在使用 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 (position > 0) { fs.Position = position; 可能有开始的 mp4 标头,就像在 flv 流中使用的那样来跟踪搜索位置,因为如果搜索位置 > 0,则无法识别流

任何人都可以帮助我。

问候。

4

1 回答 1

0

您将 Content-Length 设置为文件长度,然后只发送文件的一部分。

另外我不认为你可以像那样分割视频,我认为你必须将文件位置设置为 I 帧的开头,这意味着以某种方式解析 mp4 文件并找到最接近的 I 帧您想要的时间并将文件位置设置为该字节,然后从那里开始流式传输。

于 2015-06-15T14:20:36.757 回答