python+hls授权加密m3u8和二进制ts切片访问播放视频示例代码

代码语言:python

所属分类:其他

代码描述:python+hls授权加密m3u8和二进制ts切片访问播放视频示例代码,通过FFmpeg将MP4视频预先切片并用AES-128加密为HLS流。用户访问时需输入密码,后端验证通过后颁发一个有时效性的安全Token。前端hls.js播放器在请求解密密钥时,必须携带此Token。服务器在验证Token有效后才提供密钥,从而实现对视频内容的授权访问。播放器在浏览器内存中实时解密视频数据,确保了整个播放流程的安全性。

代码标签: python hls 授权 加密 m3u8 二进制 ts 切片 访问 播放 视频 示例 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
import os
import subprocess
from flask import Flask, jsonify, request, send_from_directory, abort, Response
from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadTimeSignature

# --- 配置 ---
INPUT_VIDEO_PATH = "input_video.mp4"
OUTPUT_FOLDER = "video_output"
KEY_FILENAME = "enc.key"
PLAYLIST_NAME = "playlist.m3u8"
CORRECT_PASSWORD = "your-strong-password"  # !!! 在生产环境中请使用更复杂的密码 !!!
TOKEN_EXPIRATION_SECONDS = 3600  # Token有效期1小时

# --- Flask 应用设置 ---
app = Flask(__name__)
# !!! 在生产环境中请务必修改为一个随机且保密的字符串 !!!
app.config['SECRET_KEY'] = 'a-super-secret-key-that-you-should-change'

# --- HTML 模板内嵌 ---
# 将前端HTML/JS/CSS代码直接放入Python字符串中
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>安全HLS视频播放器</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f0f2f5; }
        .container { text-align: center; padding: 40px; background-color: white; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        #password-form { display: block; }
        #player-container { display: none; }
        h1 { color: #333; }
        input[type="password"] { padding: 10px; font-size: 16px; border-radius: 4px; border: 1px solid #ccc; margin-right: 10px; }
        button { padding: 10px 20px; font-size: 16px; border: none; border-radius: 4px; background-color: #007bff; color: white; cursor: pointer; }
        button:hover { background-color: #0056b3; }
        #message { margin-top: 15px; color: red; }
     .........完整代码请登录后点击上方下载按钮下载查看

网友评论0