Loading
All articles
Python 7 min read

How to Generate Audio from Text with Text-to-Speech (TTS)

Turn a written script into spoken audio: try your browser’s built-in voice, then generate an MP3 with a modern text-to-speech API. Learn voice selection, SSML pronunciation fixes, and quality checks.

nbkhope
On this page

Your words are ready for a podcast intro, a language lesson, an accessible article, or a helpful voice in an app. But you don’t have a recording booth—or an hour to retake “MCP” until it sounds right. Text-to-speech (TTS) turns written text into spoken audio, often in seconds.

You can ask the browser on your own device to read a sentence, or send text to a cloud service and save an MP3. We’ll try both, then tune the pronunciation and pacing so the result sounds like a person meant to say it.

A colorful TTS workflow: clean up the script, add pronunciation and pause hints, select a language and voice, send the text to a speech engine, receive an MP3, then listen and revise.

What happens between text and sound?

A TTS system first interprets the words and their likely pronunciations. It estimates rhythm, emphasis, and intonation, then produces an audio waveform. Modern neural voices learn these patterns from speech examples, which can make a voice sound more fluid than older, rule-based synthesis.

The system is making a performance from your script. “Dr. Lee will read 3/4 of the report” can be spoken in different ways depending on context. A voice engine may not know whether 3/4 means “three quarters” or “March fourth,” or whether “MCP” should be letters or a word. That’s why a good TTS workflow includes a human listen-through.

Quick preview: make your browser speak

Most current browsers expose the Web Speech API. It uses voices available to the device, so it’s handy for a fast preview and accessibility features. This example speaks through your speakers; it does not create an MP3 file.

1<textarea id="script">Hello! Your words are ready to be heard.</textarea>
2<button id="speak">Speak</button>
3<button id="stop">Stop</button>
4
5<script>
6  const speaker = window.speechSynthesis;
7
8  document.querySelector("#speak").addEventListener("click", () => {
9    speaker.cancel(); // Clear an earlier utterance.
10    const utterance = new SpeechSynthesisUtterance(
11      document.querySelector("#script").value,
12    );
13    utterance.lang = "en-US";
14    utterance.rate = 1;
15    const localVoice = speaker.getVoices().find((voice) => voice.lang === "en-US");
16    if (localVoice) utterance.voice = localVoice;
17    speaker.speak(utterance);
18  });
19
20  document.querySelector("#stop").addEventListener("click", () => speaker.cancel());
21</script>

The device chooses which voices are installed, and voice lists can load asynchronously. If you build a real voice picker, listen for the browser’s voiceschanged event and let people choose. Use a user-initiated button, as above, because browsers may block speech that starts unexpectedly.

Generate a downloadable MP3

For a portable audio file, use a speech service that returns audio bytes. Here’s a small Python example using Google Cloud Text-to-Speech. It uses a cloud account and credentials, but no service-account key in your source code.

  1. Create or choose a Google Cloud project, enable Cloud Text-to-Speech, and configure Application Default Credentials using Google’s setup guide.
  2. Install the Python client library:
python -m pip install --upgrade google-cloud-texttospeech
  1. Save this as make_audio.py and run python make_audio.py:
1from pathlib import Path
2
3from google.cloud import texttospeech
4
5client = texttospeech.TextToSpeechClient()
6
7request_input = texttospeech.SynthesisInput(
8    text="Hello! This sentence is becoming an audio file."
9)
10voice = texttospeech.VoiceSelectionParams(
11    language_code="en-US",
12    name="en-US-Neural2-A",
13)
14audio = texttospeech.AudioConfig(
15    audio_encoding=texttospeech.AudioEncoding.MP3,
16    speaking_rate=1.0,
17)
18
19response = client.synthesize_speech(
20    input=request_input,
21    voice=voice,
22    audio_config=audio,
23)
24Path("hello.mp3").write_bytes(response.audio_content)
25print("Created hello.mp3")

The voice name is just an example: models and voice availability change, so check the provider’s current voice list and choose the locale you actually need. en-US is US English; a Portuguese script should use a Portuguese voice and language code. A voice can sound fluent and still misread a name, acronym, or local expression.

This example uses a Neural2 voice because it supports the speed setting shown here. Newer voice families can have different controls: Google currently documents Chirp 3: HD as streamable, but it does not accept SSML input or speaking-rate and pitch settings. The newest model is not automatically the best fit; choose the voice based on the controls and sound your project needs.

The important pieces are straightforward: the input is your text, the voice selects a language and voice, the audio config selects MP3, and the response contains binary audio bytes. Keep cloud credentials in the provider’s credential store or your platform’s secret manager—not in browser code or a public repository.

A mock audio-studio preview showing the script, language and voice selectors, SSML pronunciation hint, and an MP3 player with waveform and play button.

Add pronunciation and pacing hints with SSML

SSML (Speech Synthesis Markup Language) is a way to annotate text with instructions such as pauses, pronunciations, and how to read dates or abbreviations. For example:

1<speak>
2  Welcome to the demo.
3  <break time="400ms"/>
4  We’ll say <sub alias="text to speech">TTS</sub> slowly and clearly.
5</speak>

In the Python example, pass this string as texttospeech.SynthesisInput(ssml=ssml) instead of text=.... SSML is an XML standard, but providers support different subsets and extensions. Check the chosen voice’s documentation, escape XML characters such as & and < in ordinary text, and validate the markup before sending it.

SSML is especially helpful for acronyms, product names, unusual spellings, dates, and deliberate pauses. Don’t mark up every sentence. If the voice sounds stiff, simplify the hints and let its natural rhythm work.

Choose the right kind of TTS

If you need…A good place to startKeep in mind
A quick spoken preview in a web pageBrowser Web Speech APIVoice and sound vary by device; it doesn’t directly save an MP3.
A consistent audio file for a course, clip, or podcast draftHosted TTS API returning MP3 or WAVCheck language, voice, usage limits, cost, and data handling.
A voice response while a person is waitingA streaming speech APIStreaming can reduce perceived delay; check whether the feature and voice are generally available or still in preview.
Precise timing for captions or highlighting text as it’s spokenSpeech marks or word timestamps, if the provider supports themNot every voice or engine offers alignment metadata.

For a short narration, create one file and listen through it. For long scripts, split at paragraph or sentence boundaries, synthesize each section, and join the audio carefully. Cutting the text at an arbitrary character count can split a sentence or change pronunciation. Keep the same voice and settings across chunks, and check the joins for abrupt changes in volume or pace.

The human quality check: listen like an editor

Before publishing, listen to the actual audio—not just the text. Check names, acronyms, numbers, dates, punctuation, language switching, pauses, and the beginning and end of each chunk. Try the same sentence in a few voices; the best one is the voice that fits your audience and message, not necessarily the most dramatic demo.

Also check the practical details. MP3 is convenient for sharing and web playback; WAV or PCM can be useful when you plan to edit or process the audio. Avoid sending confidential text to a service unless its data practices and your permissions allow it. Use only voices you’re authorized to use, get clear permission for custom or cloned voices, and make synthetic audio clear to listeners when confusion with a real person would matter.

Your first audio in four moves

  1. Write a short script and read it aloud yourself. Fix wording that feels awkward to speak.
  2. Preview it in your browser, or generate an MP3 with the cloud example.
  3. Listen for one mistake. Add a pronunciation hint or pause, then synthesize again.
  4. Save the final audio with its language, voice, and script version so you can reproduce it later.

That’s TTS: text in, voice out, then a quick human edit. The magic is not only the voice model. It’s the script, voice choice, pronunciation hints, and your ears working together.

Sources and further reading

Thanks for reading!

Know someone who would enjoy this? Send it their way.

More articles

Read next

Python 7 min read

How to Generate Images from Text: A Practical Guide

Turn an idea into an image with a better prompt, a repeatable generation workflow, and a modern open model. Learn how to iterate, steer composition, and check the result before using it.

nbkhope

Comments

Be kind and specific. Comments with links from new accounts appear after a moderator reviews them.