在Android/Windows平台下,静态资源+h5可以毫无压力的播放视频,例如下面的代码
<video id="media" style="width: 100%; height:290px;" src="/static/video/video.mp4" autoplay="autoplay" controls>
</video>
但是到了iPhone/iPad下,使用单纯的js+html等静态页面,是行不通的,需要增加一些头部信息。无奈执行,搭建了个Django环境处理,写法如下:
def video_player( request ):
req_video_name = request.GET["name"]
return render(request,"video_player.html", {'media': req_video_name})
def video_download( request ):
const_size = 1000000
req_video = request.GET["name"]
try:
path = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/')
video_path = path + "/static/class/" + req_video
with open(video_path,"rb") as f:
HTTP_RANGE = request.META['HTTP_RANGE'].split('-')
op = int(HTTP_RANGE[0][6:])
size = os.path.getsize(video_path)
if HTTP_RANGE[1]=='':
ed = min(size-1, op+const_size-1)
else:
ed = min(int(HTTP_RANGE[1]), op+const_size-1)
s = f.read()[op:ed+1]
response = HttpResponse(s, content_type='video/mp4')
response.status_code = 206
response['Accept-Ranges'] = 'bytes'
response['Content-Length'] = ed-op+1
response['Content-Range'] = 'bytes %s-%s/%s' % (op, ed, size)
return response
except Exception as e:
logger.info(str(e))
video_player.html
{%load static%}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>odeYe</title>
<meta name="description" content="">
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
<link rel="stylesheet" href="{% static "index.css" %}" type="text/css">
<link rel="stylesheet" href={% static "ui-choose.css" %} type="text/css">
</head>
<video id="media" style="width: 100%; height:290px;" src="/lesson/video_download/?name={{media}}" autoplay="autoplay" controls>
</video>
<script>
</script>
最关键的还算video_download方法,http请求需要得到视频的大小以及播放过程中,每块的大小。为啥ios需要这么弄,我也不知道…感觉让开发者去处理,很烦啊,为啥平台自己不去干这些活呢?
ios上播放效果如下
ps:朋友给的mp4,自己处理了一下,给孩子弄个资源网站,供学习娱乐使用。对资源感兴趣的可以私聊…