About Text to Speech on the Fly

You can generated text-to-speech sound on the fly using gtts library, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from io import BytesIO
from gtts import gTTS
from django.http import HttpResponse

def create_text_to_speech_sound(request):
    text = request.POST.get("text", "Hello, Djangonauts!")
    text_to_speech = gTTS(text=text, lang="en")
    sound_data = BytesIO()
    text_to_speech.write_to_fp(sound_data)
    sound_data.seek(0)
    return HttpResponse(sound_data.read(), content_type="audio/mp3")

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Python 3 gtts