Python text to audio (Audio flash cards)
I want to begin learning a new language: Lets say French and there are many excellent resources available on platforms like YouTube. But these apps typically require an internet connection or other resources on a smartphone or laptop.
However, to make my language learning experience more effective and accessible, I am particularly focused on developing my listening skills. My goal is to keep things simple and I would like to use audio files that can be played on my compact MP3 player while I am commuting on job, walking or in gym.
Additionally, I would value the ability to update these audio files as I progress — whether it’s to add new content or remove outdated material. This flexibility would enable me to continually refine and personalize my learning experience, making the most of every opportunity to engage with the language learning process.
Selection of Tech Stack
For the sake of simplicity I have selected Python and found a fantastic library available and the library is gtts and what gtts is: gTTS (Google Text-to-Speech), a Python library and CLI tool to interface with Google text-to-speech translator API.
Get Sanjeev Tyagi’s stories in your inbox
Join Medium for free to get updates from this writer.
To begin with, let’s create a file that will serve as the foundation for generating an audio file. For this purpose, I am using the JSON format and save the file with the name “misc.json.” as sample below (french : english) :
{
"Je Suis": "I am ",
"Je suis la": "I am here",
"Je suis Pret": "I m ready ",
"Je suis content ": "I am happy",
"Je suis fatigue ": "I am tired",
"Je suis malade ": "I am sick",
"Je suis occupe ": "I am busy"
}Now, Just opened my terminal and installed gtts :
pip3 install gTTSnow writing script in file text_to_speech.py:
from gtts import gTTS
from gtts import lang
# Json format to provide text which need to convert in audio
import json
# command line argument
import argparse
import sys
import os.path
if len(sys.argv) < 2:
usage = """usage: text_to_speech: [-h] [-j JSON] [-l LANGUAGE] [-o [OPTIONS]] [-r REPETITION]
options:
-h, --help show this help message and exit
-j JSON, --json JSON Input Json file.
-l LANGUAGE, --language LANGUAGE
second language
-o OPTIONS, --options OPTIONS
List of language options available.
-r REPETITION, --repetition REPETITION
Repeat word or statement of second language. Default is 3."""
print(usage)
exit()
args_parser=argparse.ArgumentParser(prog="text_to_speech:", description="""This script was originally created to generate MP3 audio for English and French text. It's mainly useful for listening practice.""")
args_parser.add_argument("-j", "--json", help="Input Json file.")
# default is French Language
args_parser.add_argument("-l", "--language", default='fr', help="second language")
args_parser.add_argument("-o","--options", nargs='?', const=True, default=False, help="List of language options available.")
# default repetition is 3
args_parser.add_argument("-r", "--repetition", type=int, default=3, help="Repeat word or statement of second language. Default is 3.")
# parsing command line argument
# like: Json file name
# language (by default it is French)
# Available languages listing opetion
# and repetiton. default is 3
args=args_parser.parse_args()
if args.options:
for short, language in lang.tts_langs().items():
print(f"Laguage: {language} => short {short}")
exit()
## create audio directory if not exists directory
if not os.path.exists("audio"):
os.mkdir("audio")
# extracting file name from json to generate audio file with same name
fname = args.json.rsplit( ".", 1 )[0]
if not os.path.isfile("source"+ os.path.sep + args.json):
print(f"Text source file '{args.json}' not exists in folder 'source' folder. Keep text json file in folder 'source' on same location as script")
exit()
# Open source json file (sample as already provided
with open("source" + os.path.sep +fname+".json", 'r') as f:
french_words = json.load(f)
# generating mp3 audio file
with open( "audio" + os.path.sep +fname+'.mp3', 'wb') as f:
for k, v in french_words.items():
# first option is english
lang = "en"
gTTS( v + " .", lang=lang, ).write_to_fp(f)
# second language is profided by command line
lang=args.language
# with repetition from command line
for i in range(0, args.repetition):
gTTS( k + " .", lang=lang, ).write_to_fp(f)
print( f"Audio file saved as audio{os.path.sep}{fname}.mp3")
# for the sake of simplicity, I am not adding exceptions. Now, final point. Execution of script
To get help:
python text_to_speech.py -h
## output would be
usage: text_to_speech: [-h] [-j JSON] [-l LANGUAGE] [-o [OPTIONS]] [-r REPETITION]
options:
-h, --help show this help message and exit
-j JSON, --json JSON Input Json file.
-l LANGUAGE, --language LANGUAGE
second language
-o OPTIONS, --options OPTIONS
List of language options available.
-r REPETITION, --repetition REPETITION
Repeat word or statement of second language. Default is 3."""This script is designed to expect a JSON file located in the “source” folder, which should be under same directory as the script itself. Additionally, the output will be generated in a subfolder named “audio” within the same directory.
now, generate audio with sample file misc.json
python text_to_speech.py -j misc.json -l frthis command will generate audio file as misc.mp3
Enjoy …









