从零开始打造云端AI管理调度平台(番外篇_2)视频播放器

Posted 跟着皮皮实战Python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从零开始打造云端AI管理调度平台(番外篇_2)视频播放器相关的知识,希望对你有一定的参考价值。

本次更新主要更新一个html5视频播放器,用于在内容库当中的视频查看以及后续的智能处理结果查看。


视频播放一定要采用流式传输

为什么在文章刚开头我就要强调这一点。

因为很多新手小白在创建video标签时,会直接填写文件的路径,如下:

<video class="video" poster="" width="960" height="540" controls preload>
    <source src="/media/test.mp4"
            media="only screen and (min-device-width: 568px)">
    </source>
</video>

这样可以播放视频吗?

当然可以!

但是这样会带来一个很严重的问题

当你拖动进度条至未缓存部分时,你的视频会直接重新播放

而我们想实现的效果是拖动到哪里,视频从哪里开始播放

所以我们需要采用流式传输


如何实现流式传输

打开views.py,创建两个函数如下:

from wsgiref.util import FileWrapper
from django.http import StreamingHttpResponse
import mimetypes
import os
import re

#以下两个方法实现视频流式传输
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):
    path=request.GET['video_path']
    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)
    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()
        if first_byte:
            first_byte = int(first_byte)
        else:
             first_byte = 0
        last_byte = first_byte + 1024 * 1024 * 8 # 8M per piece, the maximum volume of the response body
        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

然后打开urls.py,创建视频流的地址

from django.contrib import admin
from django.urls import path
from mainbody.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('content_storage/', content_storage),
    path('get_content_media/', get_content_media),
    path('ai_cut/', ai_cut),
    path('ai_cut_taskCreate/',ai_cut_taskCreate),
    path('stream_video/', stream_video),
]

创建视频播放界面

创建check_video.html文件:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.88.1">
    <title>AI调度管理平台</title>
    <!-- Bootstrap core CSS -->
    <link href="/statics/css/bootstrap.min.css" rel="stylesheet">
    <link href="/statics/css/all.css" rel="stylesheet">
    <link href="/statics/css/myfont.css" rel="stylesheet">
    <link href="/statics/css/styles.css" rel="stylesheet">

    <style>
        .bd-placeholder-img 
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            user-select: none;
        
        
        @media (min-width: 768px) 
            .bd-placeholder-img-lg 
                font-size: 3.5rem;
            
        
</style>


    <!-- Custom styles for this template -->
    <link href="/statics/css/sidebars.css" rel="stylesheet">
</head>

<body>
    <main>
        <div class="col-2">
            <div class="d-flex flex-column flex-shrink-0 p-3 text-white bg-dark" style="height: 100vh;">
                <a href="#" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
                    <i class="fas fa-cloud" style="font-size: 30px;"></i>
                    <span class="fs-4">&nbsp; AI调度管理平台</span>
                </a>
                <hr>
                <ul class="nav nav-pills flex-column mb-auto">
                    <li class="nav-item">
                        <a href="/" class="nav-link text-white">
                            <svg class="bi me-2" width="16" height="16">
                        </svg> 主页
                        </a>
                    </li>
                    <li>
                        <a href="#" class="nav-link text-white">
                            <svg class="bi me-2" width="16" height="16">
                        </svg> 智能标签
                        </a>
                    </li>
                    <li>
                        <a href="/ai_cut/" class="nav-link text-white">
                            <svg class="bi me-2" width="16" height="16">
                        </svg> 智能拆条
                        </a>
                    </li>
                    <li>
                        <a href="#" class="nav-link text-white">
                            <svg class="bi me-2" width="16" height="16">
                        </svg> 智能唱词
                        </a>
                    </li>
                    <li>
                        <a href="#" class="nav-link text-white">
                            <svg class="bi me-2" width="16" height="16">
                        </svg> 人脸检测
                        </a>
                    </li>
                    <li>
                        <a href="#" class="nav-link active" aria-current="page">
                            <svg class="bi me-2" width="16" height="16">
                        </svg> 内容库
                        </a>
                    </li>
                </ul>
                <hr>
            </div>
        </div>
        <div class="col-10 container-fluid bg-light">
            <div class="row container-fluid bg-light">
                <header class="p-3 mb-3 border-bottom">
                    <div class="container-fluid">
                        <div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
                            <ul class="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0">
                                <li><a href="#" class="nav-link px-4 link-secondary">概况</a></li>
                                <li><a href="#" class="nav-link px-4 link-dark">用户管理</a></li>
                                <li><a href="#" class="nav-link px-4 link-dark">开发者支持</a></li>
                                <li><a href="#" class="nav-link px-4 link-dark">帮助</a></li>
                            </ul>

                            <form class="col-12 col-lg-auto mb-3 mb-lg-0 me-lg-3">
                                <input type="search" class="form-control" placeholder="Search..." aria-label="Search">
                            </form>

                            <div class="dropdown text-end">
                                <a href="#" class="d-block link-dark text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false">
                                    <img src="/statics/images/头像.jpg" alt="mdo" width="32" height="32" class="rounded-circle">
                                </a>
                                <ul class="dropdown-menu text-small" aria-labelledby="dropdownUser1">
                                    <li><a class="dropdown-item" href="#">个人信息</a></li>
                                    <li><a class="dropdown-item" href="#">安全凭证</a></li>
                                    <li><a class="dropdown-item" href="#">钱包</a></li>
                                    <li>
                                        <hr class="dropdown-divider">
                                    </li>
                                    <li><a class="dropdown-item" href="#">退出登录</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </header>
            </div>
            <div class="row my-3 mx-3 shadow">
                <div class="col-8 my-2">
                    <video class="video" poster="" width="960" height="540" controls preload>
                        <source src=" video_path "
                                media="only screen and (min-device-width: 568px)">
                        </source>
                    </video>

                </div>
                <div class="col-4 my-3">
                    <h3 class="py-3 border-bottom">视频信息</h3>
                    <div class="row my-3"><h5 class="col-3">视频名称</h5><p class="col-6">  video_name </p></div>
                    <div class="row my-3"><h5 class="col-3">视频大小</h5><p class="col-6"> video_size</p></div>
                    <div class="row my-3"><h5 class="col-3">视频长度</h5><p class="col-6"> video_dur</p></div>
                    <div class="row my-3"><h5 class="col-3">创建时间</h5><p class="col-6"> video_ctime</p></div>
                    <div class="row my-3"><h5 class="col-3">视频描述</h5><p class="col-6">暂无</p></div>
                </div>
            </div>

        </div>
    </main>


    <script src="/statics/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="/statics/js/echarts.min.js"></script>
    <script type="text/javascript" src="/statics/js/westeros.js"></script>
    <script src="/statics/js/sidebars.js"></script>
    <script src="/statics/js/jquery-3.6.0.min.js"></script>
    <script src="/statics/js/content_storage_myjs.js"></script>
    <script src="/statics/js/html5media.js"></script>

</body>

</html>

打开views.py,创建check_video函数,该函数用来渲染视频播放界面:


#内容库查看视频详情页
def check_video(request):
    if(request.method=='GET'):
        video_id=int(request.GET['id'])
        video_info=content_media.objects.filter(id__exact=video_id)
        video_name=video_info[0].name
        video_size=video_info[0].size
        video_dur=video_info[0].duration
        video_ctime=video_info[0].create_time
        video_path="/stream_video/?video_path=content_media\\\\origin\\\\aizou0629_"+video_name
        data=
            'video_name':video_name,
            'video_size':video_size,
            'video_dur':video_dur,
            'video_ctime':video_ctime,
            'video_path':video_path
        
    return render(request, 'check_video.html',data)

打开urls.py,创建视频播放界面的地址 'check_video/':

from django.contrib import admin
from django.urls import path
from mainbody.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('content_storage/', content_storage),
    path('get_content_media/', get_content_media),
    path('ai_cut/', ai_cut),
    path('ai_cut_taskCreate/',ai_cut_taskCreate),
    path('check_video/', check_video),
    path('stream_video/', stream_video),
]

修改内容库渲染函数

主要用于定义内容库每条视频最后面的查看详情的功能,代码如下:

#返回内容库数据库
def get_content_media(request):
    myDict = 'data': []
    conn=pymysql.connect(host='localhost',
                     user='root',
                     password='',#输入你的数据库密码
                     database='test')
    cursor=conn.cursor()
    sql="select * from mainbody_content_media order by create_time DESC"
    cursor.execute(sql)
    result=cursor.fetchall()
    html=''
    for each in result:
        html=html+"<tr>" \\
             "<th></th>" \\
             "<td></td>" \\
             "<td></td>" \\
             "<td></td>" \\
             "<td><i class=\\"fas fa-check-circle\\" style=\\"color:lawngreen;\\"></i></td>" \\
             "<td><a href=\\"/check_video?id=\\">查看详情</a></td></tr>".format(each[0],each[1],each[2],each[3],each[0])
    myDict['data']=html
    return HttpResponse(json.dumps(myDict), content_type='application/json')

测试一下:

视频播放界面已成功创建!

如果文章帮助到了您,可否给一个点赞关注收藏呢~

如果遇到编程上的问题,欢迎留言哦~

关注公众号:跟着皮皮实战python

关注公众号回复:aiweb,获取项目源码

了解最新最全的python实战内容

以上是关于从零开始打造云端AI管理调度平台(番外篇_2)视频播放器的主要内容,如果未能解决你的问题,请参考以下文章

[Python从零到壹] 番外篇之可视化利用D3库实现CSDN博客每日统计效果(类似github)

[Python从零到壹] 番外篇之可视化利用D3库实现CSDN博客每日统计效果(类似github)

从零开始学深度学习编译器番外一,Data Flow和Control Flow

一假期番外篇——动态规划,Leetcode121

JVM技术专题深入分析CG管理和原理查缺补漏「番外篇」

Apache Cordova开发Android应用程序——番外篇