About Creating Sounds on the Fly

You can create sounds from different audio segments on the fly in Django views, using pydub library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.http import HttpResponse
from django.conf import settings
from pydub import AudioSegment

def create_sound(request):
    original_segment = AudioSegment.from_wav(
        settings.BASE_DIR / "data" / "ding.wav"
    )
    sound = AudioSegment.silent(duration=0)
    for volume_modification in [-20, -10, 0]:
        segment = original_segment + volume_modification
        sound += segment
    sound_data = sound.export()
    return HttpResponse(sound_data, content_type="audio/mp3")

For pydub to function properly, you will also need ffmpeg utility installed in your operating system.

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Python 3 ffmpeg pydub