解决问题:
template中使用video标签播放视频时,无法快进的问题
<video src='/media/video.mp4'></video>
即使使用了预加载也无法快进(src为media路径下的文件)
利用下面这两个函数可以做到点击进度条时,视频的快进与快退(views.py文件)
def file_iterator(file_name, chunk_size=8192, offset=0, length=None):
with open(file_name, "rb") as f:
f.seek(offset, os.SEEK_SET)
remaining = length
while True:
bytes_length = chunk_size if remaining is None else min(remaining, chunk_size)
data = f.read(bytes_length)
if not data:
break
if remaining:
remaining -= len(data)
yield data
def stream_video(request):
"""将视频文件以流媒体的方式响应"""
range_header = request.META.get('HTTP_RANGE', '').strip()
range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)
range_match = range_re.match(range_header)
path = request.GET.get('path')
#这里根据实际情况改变,我的views.py在core文件夹下但是folder_path却只到core的上一层,media也在core文件夹下
folder_path = os.getcwd().replace('\\', '/')
path=folder_path+'/core/'+path #path就是template ?后面的参数的值
size = os.path.getsize(path)
content_type, encoding = mimetypes.guess_type(path)
content_type = content_type or 'application/octet-stream'
if range_match:
first_byte, last_byte = range_match.groups()
first_byte = int(first_byte) if first_byte else 0
last_byte = first_byte + 1024 * 1024 * 10
if last_byte >= size:
last_byte = size - 1
length = last_byte - first_byte + 1
resp = StreamingHttpResponse(file_iterator(path, offset=first_byte, length=length), status=206, content_type=content_type)
resp['Content-Length'] = str(length)
resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, size)
else:
resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
resp['Content-Length'] = str(size)
resp['Accept-Ranges'] = 'bytes'
return resp
需要的包有
import re
import os
import mimetypes
from wsgiref.util import FileWrapper
from django.http import StreamingHttpResponse
from django.shortcuts import render
template代码(.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="/static/js/jquery-3.3.1.js"></script>
</head>
<body>
<video id="media" src="" width="640" height="480" controls autoplay>您的浏览器不支持 video 标签 </video>
</video>
</body>
<script>
$(function () {
$("#media").attr('src', '/test_resp/?path=/media/video.mp4');
})
</script>
</html>
在url中添加路由
url('test_resp/', views.stream_video)
我的理解:加载视频不再是一个文件,而是流,每次点击进度条都会从服务器上请求新的流下来加载到video中进行播放