欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

html5 Ajax 访问.net WebApi获取视频流

程序员文章站 2024-03-30 23:57:33
src直接写入api地址,filename是对应服务器视频存储的地址。 后台对应代码 ......

http://localhost//api/Test/GetVideo?filename=/GoodVideo/e36a144b-52cd-4174-93d2-cfc41aea6c1d.mp4 是API地址加上视频路径,此地址一般是动态获取
<video id="video" style="width:100%;" controls="controls" preload="preload" onerror="videoError(this)">
<source src="http://localhost//api/Test/GetVideo?filename=/GoodVideo/e36a144b-52cd-4174-93d2-cfc41aea6c1d.mp4" type="video/mp4"> 
</video>

src直接写入api地址,filename是对应服务器视频存储的地址。

后台对应代码

 //视频接口
        public HttpResponseMessage GetVideo(string filename)
        {
            var video = new VideoStream(filename);
            Action<Stream, HttpContent, TransportContext> send = video.WriteToStream;
            var response = Request.CreateResponse();
            response.Content = new System.Net.Http.PushStreamContent(send, new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"));
            //调用异步数据推送接口  
            return response;
        }  
VideoStream 帮助类代码如下
  public class VideoStream
    {
        private readonly string _filename;

        public VideoStream(string filename)
        {
            _filename = HttpContext.Current.Server.MapPath("~" + filename); ;
        }
        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, FileShare.ReadWrite))
                {
                    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();
            }
        }  
    }

上一篇: C++_自引用指针this

下一篇: