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(); } } }