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.

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.2 Django 3.2 Django 2.2 Python 3 ffmpeg ffmpeg-python