我正在尝试使用MVC站点中的WebAPI来使用PushStreamContent对象来流式传输视频。我已经阅读了几篇关于这方面的文章(包括this frequently cited post @ strathweb.com ),似乎仍然不能让它工作。
目前,该视频不能在浏览器中播放。只要用户将鼠标移到视频控件上,它们就会变为禁用状态。服务器上出现了两个奇怪的问题/症状:
首先,在页面加载时,服务器似乎会立即回传整个文件,即使用户还没有尝试实际播放视频(他们只是看到标准的HTML5视频占位符-他们应该单击播放来查看视频)。视频标签中未指定自动播放。我可以通过流循环中的debug.writeline调用来看到这一点。
其次,当用户确实单击了play时,会发生此错误:远程主机关闭了连接。错误代码为0x800704CD。
下面是我的代码:
public class VideoController : ApiController
{
[ActionName("Get")]
public System.Net.Http.HttpResponseMessage Get(string fsoId)
{
var videoFullPath = GetPathToVideo(fsoId);
var response = Request.CreateResponse();
response.Content = new System.Net.Http.PushStreamContent( async (outputStream, context, transport) =>
{
try
{
var buffer = new byte[65536];
using (var videoFile = System.IO.File.Open(videoFullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
var length = (int)videoFile.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = videoFile.Read(buffer, 0, Math.Min(length, buffer.Length));
System.Diagnostics.Debug.WriteLine(string.Format("Length at Start: {0}; bytesread: {1}", length, bytesRead));
await
outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
catch (System.Web.HttpException httpEx)
{
System.Diagnostics.Debug.WriteLine(httpEx.GetBaseException().Message);
if (httpEx.ErrorCode == -2147023667) // The remote host closed the connection.
return;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.GetBaseException().Message);
return;
}
finally
{
outputStream.Close();
}
},
new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"));
return response;
}
}这是我的视频标签:
<video width="320" height="240" controls>
<source src="api/video/12345" type="video/mp4">
Your browser does not support the video tag.
</video>发布于 2015-04-23 02:59:45
我发现问题出在哪里:是视频出了问题。该视频的格式尚未设置为快速启动(元数据位于文件的开头)。因此,使用下面的ffmpeg命令重新生成视频可以做到这一点:
ffmpeg -1 MyVideo.mp4 -movflags faststart MyNewVideo.mp4本质上,浏览器请求/下载整个视频文件,以便读取最后嵌入的元数据。
一旦我修复了这个问题,就不会再下载整个文件,也不会再出现“远程主机关闭连接”错误。不是最直观的错误消息。
如果有人知道如何在一开始就确定现有视频是否具有元数据,我很想听听如何做到这一点。
我希望这对某些人有帮助。
https://stackoverflow.com/questions/29762159
复制相似问题