我正在编写一个 ASP.NET (C#) Web 应用程序,人们应该能够在其中通过 FileStream 从我们的 SQL Server 加载视频。由于其简单性,我正在考虑使用 HTML5 视频控件。我已经设法让它适用于保存在项目中的 mp4 文件:
<video controls id="vidPlayer" runat="server" width="420">
<source src="Content/Video/video.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
这在文件存在时起作用,但是如果我正在考虑从 FileStream 提供视频,我最终会得到一个字节数组,但我不知道如何从那里处理它。我目前有代码:
SqlConnection con = new SqlConnection(constr);
con.Open();
//Retrieve the FilePath() of the video file
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = con;
sqlCommand.CommandText = "SELECT EvidenceFS FROM [EP].[t_TraineeUploadedEvidence] WHERE ID = 'A5E262F8-6465-41C1-BD34-42EBCB492C87'";
byte[] buffer = (byte[])sqlCommand.ExecuteScalar();
MemoryStream ms = new MemoryStream(buffer);
vidPlayer.Src = ????
//Cleanup
con.Close();
我忍不住觉得我只是缺少一些简单的东西......我希望它很简单!我是这个领域的新手,所以我们将不胜感激!
如果您需要我提供更多信息,请告诉我!我也必须对音频做同样的事情,但我希望任何解决方案都能解决这两个问题。
最佳答案
这是我用的。
[HttpGet, Route("yourApi")]
public HttpResponseMessage grabMyStream(string fileName)
{
string mimeType = MimeMapping.GetMimeMapping(fileName);
MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse(mimeType);
Stream inputStream = getYourStream();
var response = Request.CreateResponse();
response.Content = new PushStreamContent(
async (outputStream, httpContent, transportContext) =>
{
byte[] buffer = new byte[65536];
int read = 0;
while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
await outputStream.WriteAsync(buffer, 0, buffer.Length);
}
}, mediaType);
return response;
}
<video controls id="vidPlayer" runat="server" width="420">
<source src="yourApi?fileName=video.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
在传递文件名时使用查询字符串,因为末尾有扩展名。
编辑:getYourStream() 方法是您返回 MemoryStream 的地方。当您的 HTML 加载时,HTML5 视频将向 src 发送 GET 请求。所以 src 需要指向你的 API 方法。这是假设您使用的是 Asp.Net Web Api。
注意:如果您从某处逐条拉取流,那么您可以将其直接写入 outputStream。这是以一种允许您一次拥有整个流然后逐段流式传输的方式编写的。它效率低下,但这是我项目的要求。如果您不必一次流一点点并且一次拥有整个流(看起来像),那么我会从您的 Api 方法中返回整个流。
关于c# - HTML5 视频 - 从 SQL 文件流流式传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36478158/