About Creating a Melody on the Fly

You can use the gensound library to create simple melodies in Django views on the fly, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.http import HttpResponse
from django.core.files.temp import NamedTemporaryFile
from gensound import Sine

def create_music(request):
    s = Sine("B A G E D# A4 A4 B4 G4 G4", duration=0.5e3)
    temporary_file = NamedTemporaryFile(
        suffix=".wav",
        delete=True,
    )
    s.export(temporary_file.name)
    return HttpResponse(
        temporary_file.read(),
        content_type="audio/wav",
    )

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2 Python 3 gensound