通过 HTTP 一个接一个地传输多个 mp4 文件

问题描述 投票:0回答:0

尝试读取多个 mp4 文件并使用 FastAPI 的 StreamingResponse 通过相同的 HTTP 端点将它们一个接一个地串联起来。然而,这两种方法都没有产生预期的结果。我想我需要将每个 mp4 生成为原子块而不是整个文件?有什么想法吗?

服务器.py

import uvicorn
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import os
import cv2

app = FastAPI()


# PROBLEM: Stops after first mp4 played
def read_multiple_files_as_one():
    count = 0
    for file_name in os.listdir('./examples'):
        if file_name.endswith(".mp4"):
            with open('./examples/' + file_name, 'rb') as f_in:
                # video = f_in.read()
                yield from f_in

@app.get("/video")
async def main():
    return StreamingResponse(read_multiple_files_as_one(), media_type="video/mp4")


# PROBLEM: Wrong frame rate
# PROBLEM: No sound
def read_multiple_files_as_one_2():
    count = 0
    for file_name in os.listdir('./examples'):
        if file_name.endswith(".mp4"):
            cam = cv2.VideoCapture(
                './examples/' + file_name)

            while True:
                success, frame = cam.read()
                if not success:
                    break
                else:
                    ret, buffer = cv2.imencode('.jpg', frame)
                    frame = buffer.tobytes()

                    count +=1
                    # print(f'frame #: {count}')

                    yield (b'--frame\r\n'
                        b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.get("/video2")
async def main():
    return StreamingResponse(read_multiple_files_as_one_2(), media_type="multipart/x-mixed-replace;boundary=frame")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

index.html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <video width="1280" height="720" autoplay controls muted>
      <source src="http://localhost:8000/video" type="video/mp4" />
    </video>

    <img src="http://localhost:8000/video2" />
  </body>
</html>
python http video stream fastapi
© www.soinside.com 2019 - 2024. All rights reserved.