About Generating MPG Videos with Sound on the Fly

You can create MP4 videos with sound out of images and audio files using the ffmpeg-python library and ffmpeg utility, as follows:

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import ffmpeg
from django.http import HttpResponse
from django.conf import settings
from django.core.files.temp import NamedTemporaryFile

def create_video_with_sound(request):
    temporary_file = NamedTemporaryFile(
        suffix=".mp4",
        delete=True,
    )
    video_input1 = ffmpeg.input(str(settings.BASE_DIR / "data" / "1.jpg"))
    video_input2 = ffmpeg.input(str(settings.BASE_DIR / "data" / "2.jpg"))
    video_input3 = ffmpeg.input(str(settings.BASE_DIR / "data" / "3.jpg"))
    sound_input = ffmpeg.input(str(settings.BASE_DIR / "data" / "ding.wav"))
    video1 = video_input1.video.hflip()
    video2 = video_input2.video.hflip()
    video3 = video_input3.video.hflip()
    audio = sound_input.audio
    joined = ffmpeg.concat(
        video1,
        audio,
        video2,
        audio,
        video3,
        audio,
        v=1,
        a=1,
    ).node
    final_video = joined[0]
    final_audio = joined[1]
    out, err = (
        ffmpeg.output(
            final_video,
            final_audio,
            temporary_file.name,
            vcodec="libx264",
            acodec="aac",
            audio_bitrate="192k",
        )
        .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