Last active 1611817310

A simple flask server to encode a specified video/audio file and stream the chunks with a generator

ffmpeg_flask_stream.py Raw
1#!/usr/bin/env python3
2from subprocess import Popen, PIPE
3from flask import Flask, Response
4import os.path
5
6app = Flask(__name__)
7PREFIX = "/media/storage"
8FORMAT = ("mp3", "audio/mpeg")
9
10def ffmpeg_generator(fn):
11 process = Popen(["ffmpeg", "-hide_banner", "-loglevel", "panic", "-i", fn, "-f", FORMAT[0], "-"], stdout=PIPE)
12 while True:
13 data = process.stdout.read(1024)
14 if not data:
15 break
16 yield data
17
18@app.route("/")
19@app.route("/favicon.ico")
20def nothing():
21 return "", 404
22
23@app.route("/<path:path>")
24def play(path):
25 path = os.path.normpath("/" + path).lstrip("/")
26 return Response(ffmpeg_generator(os.path.join(PREFIX, path)), mimetype=FORMAT[1])
27
28if __name__ == "__main__":
29 app.run()