天天看點

ASP.NET WEBAPI異步視訊流實作

要執行異步流任務,可以使用PushStreamContent。它允許伺服器逐漸推到接收用戶端的資料包。

本示例中,從伺服器的硬碟上的檔案讀取視訊流并重新整理到用戶端 (使用PushStreamContent) 65536 位元組的資料包。流媒體視訊播放然後可以立即開始 (用戶端不需要等待整個視訊來沖進),而伺服器異步寫入用戶端,這樣不會造成不必要的負載。一旦用戶端斷開連接配接,将停止寫作。

public PushStreamContent(Action<Stream, HttpContent, TransportContext> onStreamAvailable); 可以參考MSND相關說明

伺服器以WEB API 來建構

1.注冊路由

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;


namespace WebApplication2
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.MapHttpRoute(
               "DefaultVideo",
                "api/{controller}/{ext}/{filename}"
            );

        }
    }
}
           

2.實作異步發送

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;

namespace WebApplication2
{
    public class VideoStream
    {
        private readonly string _filename;

        public VideoStream(string filename, string ext)
        {
            _filename = @"D:\Downloads\" + filename + "." + ext;
        }
        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[65536];

                using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
                {
                    var length = (int)video.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (HttpException ex)
            {
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }
    }

}
           

3.實作WEBAPI接口

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

namespace WebApplication2
{
    public class VideosController : ApiController
    {
        public HttpResponseMessage Get(string filename, string ext)
        {
            var video = new VideoStream(filename, ext);
            Action<Stream , HttpContent , TransportContext> send=video.WriteToStream;
            var response = Request.CreateResponse();
            response.Content = new System.Net.Http.PushStreamContent(send,new MediaTypeHeaderValue("video/" + ext));
//調用異步資料推送接口
            return response;
        }
    }
}
           

4.實作一個HTML5頁面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <video width="480" height="320" controls="controls" autoplay="autoplay">
        <source src="/api/Videos/MP4/2" type="video/mp4">
    </video>
</body>

</html>