About Generating MP4 Videos on the Fly

You can generate MP4 videos in a Django view on the fly using ffmpeg-python library. Note that ffmpeg utility should also be installed in your operating system.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import ffmpeg
from django.http import HttpResponse
from django.conf import settings
from django.core.files.temp import NamedTemporaryFile

def create_video(request):
    temporary_file = NamedTemporaryFile(
        suffix=".mp4",
        delete=True,
    )
    # ffmpeg -framerate 1/4 -pattern_type glob -i '*.jpg' \
    # -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4
    out, err = (
        ffmpeg.input(
            str(settings.BASE_DIR / "data" / "*.jpg"),
            pattern_type="glob",
            framerate="1/4",
        )
        .output(
            temporary_file.name,
            vcodec="libx264",
            vf="fps=25",
            pix_fmt="yuv420p",
        )
        .overwrite_output()
        .run()
    )
    video_data = temporary_file.read()
    return HttpResponse(video_data, content_type="video/mp4")

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2 Python 3 ffmpeg ffmpeg-python