http://localhost//api/Test/GetVideo?filename=/GoodVideo/e36a144b-52cd-4174-93d2-cfc41aea6c1d.mp4 是API地址加上视频路径,此地址一般是动态获取
<video id="video" style="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(); } } }