Last modified: May 24, 2021

How to Convert Text to Speech in Django

In this Django tutorial, I'll show you how to convert text to speech.
We'll use the Django-Gtts library.

Django-Gtts: convert text to speech (.mp3) and cache the file.

Install Django-Gtts

Install via pip:

pip install Django-Gtts

Add gTTS to the settings.py in INSTALLED_APPS:


INSTALLED_APPS = [
    'gTTS',
    ...
]

How to use Django-Gtts

Working with Template:

Syntax:


{% load gTTS %}
<audio
    src="{% say 'language' 'text to say' %}"
    controls
></audio>

Example:


{% load gTTS %}

<audio
    src="{% say 'en-us' 'Django is a high-level Python Web framework' %}"
    controls
></audio>

Result:

How to Convert Text to Speech in Django

List of supported languages:


'af' : 'Afrikaans' 'sq' : 'Albanian' 'ar' : 'Arabic' 'hy' : 'Armenian' 'bn' : 'Bengali' 'ca' : 'Catalan' 'zh' : 'Chinese' 'zh-cn' : 'Chinese (Mandarin/China)' 'zh-tw' : 'Chinese (Mandarin/Taiwan)' 'zh-yue' : 'Chinese (Cantonese)' 'hr' : 'Croatian' 'cs' : 'Czech' 'da' : 'Danish' 'nl' : 'Dutch' 'en' : 'English' 'en-au' : 'English (Australia)' 'en-uk' : 'English (United Kingdom)' 'en-us' : 'English (United States)' 'eo' : 'Esperanto' 'fi' : 'Finnish' 'fr' : 'French' 'de' : 'German' 'el' : 'Greek' 'hi' : 'Hindi' 'hu' : 'Hungarian' 'is' : 'Icelandic' 'id' : 'Indonesian' 'it' : 'Italian' 'ja' : 'Japanese' 'km' : 'Khmer (Cambodian)' 'ko' : 'Korean' 'la' : 'Latin' 'lv' : 'Latvian' 'mk' : 'Macedonian' 'no' : 'Norwegian' 'pl' : 'Polish' 'pt' : 'Portuguese' 'ro' : 'Romanian' 'ru' : 'Russian' 'sr' : 'Serbian' 'si' : 'Sinhala' 'sk' : 'Slovak' 'es' : 'Spanish' 'es-es' : 'Spanish (Spain)' 'es-us' : 'Spanish (United States)' 'sw' : 'Swahili' 'sv' : 'Swedish' 'ta' : 'Tamil' 'th' : 'Thai' 'tr' : 'Turkish' 'uk' : 'Ukrainian' 'vi' : 'Vietnamese' 'cy' : 'Welsh'



If you want to send a text from views, follow this code:

views.py:


def index(request):
    obj = "Text From Views"
    return render(request, 'index.html', {'obj':obj})

index.html:


{% load gTTS %}

<audio
    src="{% say 'en-us' obj %}"
    controls
></audio>



Working with Views:

To use Django-Gtts in views, we will import the say() function.


from gTTS.templatetags.gTTS import say

say() function: convert text to speech and return the path of mp3 file.

Example:

views.py:


def index(request):
    obj = say(language='en-us', text="Text From Views")
    return render(request, 'index.html', {'obj':obj})


index.html:


<audio
    src="{{obj}}"
    controls
></audio>


view-source:

How to Convert Text to Speech in Django