Skip to navigation

Tutorial: Narrate an Article into One Audio File

Build a small Python script that turns a multi-paragraph article into one WAV file, step by step.

View as Markdown

In this tutorial you build narrate.py, a short Python script that reads an article from a text file and saves it as one narrated audio file.

This is what your script makes by the end:

You get there in five steps. You run the script at the end of every step, so you always have something that works:

  1. Set up a project folder.
  2. Turn one sentence into audio.
  3. Split the article into short pieces.
  4. Turn every piece into audio.
  5. Join the pieces into one file.

It takes about 15 minutes. The script uses only the Python standard library, so there is nothing to install.

Before you start

You need:

  • Python 3.9 or later. Check with python3 --version.
  • A Smallest AI API key. If you don’t have one yet, follow Step 1 of the Quickstart, then come back.
  • About 1,600 characters of TTS credit. That’s all the text the tutorial sends, from start to finish.

Step 1: Set up a project folder

Make a folder for the tutorial and move into it:

mkdir narrate-tutorial
cd narrate-tutorial

Export your API key in the same terminal. The script reads it from there:

export SMALLEST_API_KEY="your-api-key-here"

Save the text below as article.txt in the folder. Keep the empty lines between the paragraphs:

article.txt
Every lighthouse has its own signature. Sailors learn to tell them apart at night by counting the flashes and the dark gaps between them. One light might flash twice every ten seconds; the next one along the coast might shine steadily, then go dark for three.
Before radio and satellite navigation, these patterns were the difference between a safe harbour and a rocky shore. Keepers lived beside the lamp, trimming wicks, polishing lenses and winding the clockwork that turned the light through the night.
Today most lighthouses run on their own. Solar panels charge the batteries, and an LED lamp does the work that once needed a family to keep it burning. The towers still stand, though, and many of them still flash the same signature they did a hundred years ago.

Your folder has one file, article.txt, and SMALLEST_API_KEY is exported in this terminal.

Step 2: Turn one sentence into audio

Start with the smallest thing that works: one sentence, one audio file.

Create a file called narrate.py in the folder and paste in this code:

narrate.py
import json
import os
import urllib.request
API_KEY = os.environ["SMALLEST_API_KEY"]
TTS_URL = "https://api.smallest.ai/waves/v1/tts"
def synthesize(text, path):
"""Turn one piece of text into a WAV file."""
body = json.dumps({
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}).encode()
request = urllib.request.Request(TTS_URL, data=body, headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Accept": "audio/wav",
})
with urllib.request.urlopen(request) as response:
audio = response.read()
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path} ({len(audio):,} bytes)")
if __name__ == "__main__":
synthesize("Every lighthouse has its own signature.", "test.wav")

Run it:

python3 narrate.py

You should see one line. Your byte count will be a little different:

Saved test.wav (114,284 bytes)

Open test.wav and listen. The voice meher reads the first sentence of the article.

test.wav plays the sentence “Every lighthouse has its own signature.”

The synthesize function does one job: it sends one piece of text and saves the audio it gets back. You’ll use it, unchanged, in every step from here on.

What you seeWhat to do
KeyError: 'SMALLEST_API_KEY'The key isn’t exported in this terminal. Run the export line from Step 1, then run the script again
urllib.error.HTTPError: HTTP Error 401: UnauthorizedThe key is wrong or was revoked. Copy it again from the API Keys page and export it
CERTIFICATE_VERIFY_FAILED on macOSPython from python.org starts without root certificates. Open your Python folder in Applications, run Install Certificates.command, then try again

Step 3: Split the article into short pieces

One request can carry up to 8,000 characters, and we recommend about 250 per request. Real articles are often longer, so the script first splits the text into pieces of 250 characters or less. Each piece ends on a full sentence, so no word is cut in half.

This step makes no audio, so it costs nothing. You check the pieces before you pay for them.

Replace everything in narrate.py with this code. The highlighted lines are new:

narrate.py
import json
import os
import re
import urllib.request
API_KEY = os.environ["SMALLEST_API_KEY"]
TTS_URL = "https://api.smallest.ai/waves/v1/tts"
def synthesize(text, path):
"""Turn one piece of text into a WAV file."""
body = json.dumps({
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}).encode()
request = urllib.request.Request(TTS_URL, data=body, headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Accept": "audio/wav",
})
with urllib.request.urlopen(request) as response:
audio = response.read()
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path} ({len(audio):,} bytes)")
MAX_CHARS = 250
def split_into_chunks(article):
"""Split text into pieces of at most MAX_CHARS, ending on full sentences."""
chunks = []
for paragraph in article.split("\n\n"):
# Break the paragraph after every . ! or ? that has a space after it.
sentences = re.sub(r"([.!?])\s+", r"\1\n", paragraph.strip()).splitlines()
current = ""
for sentence in sentences:
if current and len(current) + 1 + len(sentence) > MAX_CHARS:
chunks.append(current)
current = sentence
else:
current = f"{current} {sentence}".strip()
if current:
chunks.append(current)
return chunks
if __name__ == "__main__":
article = open("article.txt", encoding="utf-8").read()
for number, chunk in enumerate(split_into_chunks(article), start=1):
print(f"{number}. ({len(chunk)} chars) {chunk}")

What changed:

  • import re at the top, for splitting text.
  • A new split_into_chunks function below synthesize.
  • The bottom of the file now prints the pieces instead of making audio.

Run it:

python3 narrate.py

You should see five numbered pieces:

1. (137 chars) Every lighthouse has its own signature. Sailors learn to tell them apart at night by counting the flashes and the dark gaps between them.
2. (121 chars) One light might flash twice every ten seconds; the next one along the coast might shine steadily, then go dark for three.
3. (246 chars) Before radio and satellite navigation, these patterns were the difference between a safe harbour and a rocky shore. Keepers lived beside the lamp, trimming wicks, polishing lenses and winding the clockwork that turned the light through the night.
4. (151 chars) Today most lighthouses run on their own. Solar panels charge the batteries, and an LED lamp does the work that once needed a family to keep it burning.
5. (109 chars) The towers still stand, though, and many of them still flash the same signature they did a hundred years ago.

Five pieces, each 250 characters or less, each ending with a full stop.

Look at pieces 1 and 2. They are both from the first paragraph. All three of its sentences together come to more than 250 characters, so the paragraph was split in two. A new paragraph always starts a new piece.

Step 4: Turn every piece into audio

Now send each piece to the API and save it as its own numbered file in a parts folder.

Replace everything in narrate.py with this code. The highlighted lines are new:

narrate.py
import json
import os
import re
import urllib.request
API_KEY = os.environ["SMALLEST_API_KEY"]
TTS_URL = "https://api.smallest.ai/waves/v1/tts"
def synthesize(text, path):
"""Turn one piece of text into a WAV file."""
body = json.dumps({
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}).encode()
request = urllib.request.Request(TTS_URL, data=body, headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Accept": "audio/wav",
})
with urllib.request.urlopen(request) as response:
audio = response.read()
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path} ({len(audio):,} bytes)")
MAX_CHARS = 250
def split_into_chunks(article):
"""Split text into pieces of at most MAX_CHARS, ending on full sentences."""
chunks = []
for paragraph in article.split("\n\n"):
# Break the paragraph after every . ! or ? that has a space after it.
sentences = re.sub(r"([.!?])\s+", r"\1\n", paragraph.strip()).splitlines()
current = ""
for sentence in sentences:
if current and len(current) + 1 + len(sentence) > MAX_CHARS:
chunks.append(current)
current = sentence
else:
current = f"{current} {sentence}".strip()
if current:
chunks.append(current)
return chunks
if __name__ == "__main__":
article = open("article.txt", encoding="utf-8").read()
os.makedirs("parts", exist_ok=True)
for number, chunk in enumerate(split_into_chunks(article), start=1):
synthesize(chunk, f"parts/part-{number:02d}.wav")

What changed: only the bottom of the file. It makes a parts folder and calls synthesize once for each piece.

Run it:

python3 narrate.py

The script sends five requests, one after another, in about 10 seconds. Your byte counts will be a little different:

Saved parts/part-01.wav (317,324 bytes)
Saved parts/part-02.wav (327,884 bytes)
Saved parts/part-03.wav (628,124 bytes)
Saved parts/part-04.wav (422,684 bytes)
Saved parts/part-05.wav (237,644 bytes)

The numbers in the file names have two digits (01, 02), so the files stay in reading order when you list them.

The parts folder has five files, part-01.wav to part-05.wav. Play part-03.wav to hear the whole second paragraph.

Step 5: Join the pieces into one file

The last step joins the five parts, in order, into article.wav. Python’s built-in wave module can do this, because every part has the same format: 24,000 Hz, 16-bit, mono WAV.

Replace everything in narrate.py with this code. The highlighted lines are new:

narrate.py
import json
import os
import re
import urllib.request
import wave
API_KEY = os.environ["SMALLEST_API_KEY"]
TTS_URL = "https://api.smallest.ai/waves/v1/tts"
def synthesize(text, path):
"""Turn one piece of text into a WAV file."""
body = json.dumps({
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}).encode()
request = urllib.request.Request(TTS_URL, data=body, headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Accept": "audio/wav",
})
with urllib.request.urlopen(request) as response:
audio = response.read()
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path} ({len(audio):,} bytes)")
MAX_CHARS = 250
def split_into_chunks(article):
"""Split text into pieces of at most MAX_CHARS, ending on full sentences."""
chunks = []
for paragraph in article.split("\n\n"):
# Break the paragraph after every . ! or ? that has a space after it.
sentences = re.sub(r"([.!?])\s+", r"\1\n", paragraph.strip()).splitlines()
current = ""
for sentence in sentences:
if current and len(current) + 1 + len(sentence) > MAX_CHARS:
chunks.append(current)
current = sentence
else:
current = f"{current} {sentence}".strip()
if current:
chunks.append(current)
return chunks
def join_wavs(paths, output_path):
"""Write the WAV files in paths, in order, into one WAV file."""
with wave.open(output_path, "wb") as output:
for index, path in enumerate(paths):
with wave.open(path, "rb") as part:
if index == 0:
output.setparams(part.getparams())
output.writeframes(part.readframes(part.getnframes()))
with wave.open(output_path, "rb") as result:
seconds = result.getnframes() / result.getframerate()
print(f"Saved {output_path} ({seconds:.1f} seconds of audio)")
if __name__ == "__main__":
article = open("article.txt", encoding="utf-8").read()
os.makedirs("parts", exist_ok=True)
part_paths = []
for number, chunk in enumerate(split_into_chunks(article), start=1):
path = f"parts/part-{number:02d}.wav"
synthesize(chunk, path)
part_paths.append(path)
join_wavs(part_paths, "article.wav")

What changed:

  • import wave at the top, for reading and writing WAV files.
  • A new join_wavs function below split_into_chunks.
  • The bottom of the file now keeps a list of the parts and joins them at the end.

Run it:

python3 narrate.py

The script makes the five parts again, then joins them. Your numbers will be a little different:

Saved parts/part-01.wav (341,804 bytes)
Saved parts/part-02.wav (348,044 bytes)
Saved parts/part-03.wav (593,324 bytes)
Saved parts/part-04.wav (409,004 bytes)
Saved parts/part-05.wav (249,164 bytes)
Saved article.wav (40.4 seconds of audio)

Play article.wav. You hear the whole article, from “Every lighthouse has its own signature” to “a hundred years ago”, in one file. It should sound like the sample at the top of this page.

Listen for the places where one part ends and the next begins. Each part ends with a short silence, so the joins sound like the ordinary pause between two sentences.

article.wav holds about 40 seconds of audio: the whole article, read in one voice.

Your folder now looks like this:

narrate-tutorial/
├── article.txt
├── article.wav
├── narrate.py
├── test.wav
└── parts/
├── part-01.wav
├── part-02.wav
├── part-03.wav
├── part-04.wav
└── part-05.wav

What you built

You have a script that narrates a text file. Along the way you:

  • Sent a text to speech request using only the Python standard library.
  • Split an article into pieces of 250 characters or less that end on full sentences.
  • Saved each piece as its own WAV file, in reading order.
  • Joined the pieces into one WAV file.

Try it on your own writing: put your text in article.txt and run python3 narrate.py again.

Where to go next

Need Help?