关于视频播放的断点续传实现(.NET)

在实现视频播放功能时,如果不是采用了CDN服务器,而是将视频播放文件直接放在了站点下,这时考虑采用断点续传,有利于优化播放速度。而且,大多数播放器支持缓冲播放。

闲话不多说,直接上代码:

using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Video3dApp.Controllers
{
	public class Video3dController : Controller
	{

		public ActionResult BrandUSA() {
			return View();
		}

		public ActionResult Detail() {
			return View();
		}
		
		[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post | HttpVerbs.Options)]
		public void ReadVideo() {
			var reqRange = Request.Headers["Range"];
			string[] reqBlockRange = null;
			if ( !string.IsNullOrEmpty(reqRange) ) {
				reqBlockRange = reqRange.Replace("bytes=", "").Split('-');
				Response.StatusCode = 206;
				Response.AddHeader("status", "206");
			}

			Response.AddHeader("accept-ranges", "bytes");
			Response.AddHeader("access-control-allow-methods", "HEAD, GET, OPTIONS");
			Response.AddHeader("access-control-allow-origin", "*");
			Response.AddHeader("cache-control", "public, max-age=30726563");
			Response.AddHeader("content-disposition", $"attachment;  filename=test.mp4");
			Response.ContentType = "video/mp4";

			string fileName = Server.MapPath("/UploadFiles/test.mp4");

			using ( var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )
			using (var reader=new BinaryReader(stream)) {
				long fileSize = stream.Length;

				long startPosition = 0;
				long partialSize = fileSize;
				if ( reqBlockRange != null ) {
					startPosition = Convert.ToInt32(reqBlockRange[0]);
					partialSize = fileSize - startPosition;
				}

				//Read partial content into the buffer with a specified size
				byte[] buffer = new byte[(int)partialSize];
				// go to offset address 
				reader.BaseStream.Seek(startPosition, SeekOrigin.Begin);

				// fill buffer from starting at address to address + BlockSise
				reader.Read(buffer, 0, (int)partialSize);
				Response.AddHeader("content-range", $"bytes {startPosition}-{startPosition + partialSize - 1}/{fileSize}");
				Response.AddHeader("Content-Length", $"{partialSize}");
				Response.BinaryWrite(buffer);
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值