Speech Recognition and Speech Synthesis

Updated · 10 min read
hardPython 3.13aispeech-recognitiontext-to-speechwhisperaudioword-error-rate

Speech recognition, also called speech-to-text or automatic speech recognition (ASR), turns spoken audio into written text. Speech synthesis, or text-to-speech (TTS), does the opposite: it turns text into a spoken voice. Together they power voice assistants, live captions, dictation, phone menus and screen readers.

Both are neural networks, like the image models in this chapter. They work on sound turned into numbers, and modern speech recognizers turn sound into a picture-like grid called a spectrogram first.

What Speech AI Does

TaskDescription
Speech-to-text (ASR)It is used to write down what was said: captions, dictation, meeting notes
Text-to-speech (TTS)It is used to read text aloud in a natural voice: screen readers, navigation, assistants
Speaker recognitionIt is used to tell who is speaking, for example to label speakers in a meeting
Speech translationIt is used to turn speech in one language into text or speech in another
Voice cloningIt is used to copy a real person's voice from a short sample; it needs that person's consent

Example: Sound Is a List of Numbers

The programs in this chapter need pip install torch transformers pillow scipy scikit-learn. The first run downloads each pretrained model from Hugging Face; the download and loading messages are left out of the output shown.

A microphone measures air pressure thousands of times per second. Each measurement is a sample, and the sample rate is how many samples are taken per second.

Python
import numpy as np
from scipy.io import wavfile
 
rate = 16000                                         # samples per second (16 kHz, used by most speech models)
t = np.arange(rate) / rate                           # one second of time points
tone = 0.5 * np.sin(2 * np.pi * 440 * t)             # a 440 Hz tone: the musical note A
 
print("Samples in one second:", len(tone))
print("First 5 samples:", np.round(tone[:5], 4))
print("Loudest value:", round(tone.max(), 4))
 
wavfile.write("tone.wav", rate, (tone * 32767).astype(np.int16))   # 16-bit WAV file
rate_back, samples = wavfile.read("tone.wav")
print("Read back:", rate_back, "Hz,", len(samples), "samples,", samples.dtype)
 
# Which frequencies are in the sound? The Fourier transform finds them.
spectrum = np.abs(np.fft.rfft(tone))
print("Strongest frequency:", np.fft.rfftfreq(len(tone), 1 / rate)[spectrum.argmax()], "Hz")
Output
Samples in one second: 16000
First 5 samples: [0.     0.086  0.1694 0.2477 0.3187]
Loudest value: 0.5
Read back: 16000 Hz, 16000 samples, int16
Strongest frequency: 440.0 Hz

Explanation:

  • 16,000 samples per second (16 kHz) is the rate most speech models use; music is usually recorded at 44,100 or 48,000.
  • The tone is a sine wave, so the samples rise smoothly from 0. A value of 0.5 is half the loudest possible sound.
  • WAV files usually store each sample as a 16-bit whole number, from -32,768 to 32,767, so the program scales by 32,767 before saving.
  • The Fourier transform (np.fft.rfft) finds which frequencies make up a sound. It finds exactly 440 Hz, the pitch of the tone.

How Speech Models Hear

StepWhat happens
1. AudioA list of samples, usually resampled to 16 kHz
2. SpectrogramThe sound is cut into short slices (about 25 milliseconds, every 10 milliseconds), and the Fourier transform measures each frequency in each slice
3. Mel scaleFrequencies are grouped the way human hearing works, finer at low pitches; Whisper uses 80 groups
4. Neural networkAn encoder reads the spectrogram like an image; a decoder writes the text one token at a time, like a language model

Example: Text to Speech

This program uses MMS-TTS, an open text-to-speech model from Meta, to read a school announcement aloud. The model is free for learning and other non-commercial use (license CC BY-NC 4.0).

Python
import numpy as np
import torch
from scipy.io import wavfile
from transformers import AutoTokenizer, VitsModel
 
# MMS-TTS English: a text-to-speech model from Meta (license CC BY-NC 4.0, for non-commercial use)
tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-eng")
model = VitsModel.from_pretrained("facebook/mms-tts-eng")
 
text = "The science fair is on Friday at ten in the school library."
inputs = tokenizer(text, return_tensors="pt")
print("Characters in:", len(text), "| tokens:", inputs["input_ids"].shape[1])
 
torch.manual_seed(0)                                 # the model adds a little randomness to speech timing
with torch.no_grad():
    audio = model(**inputs).waveform[0].numpy()
 
rate = model.config.sampling_rate
print("Sample rate:", rate, "Hz | samples:", f"{len(audio):,}", f"| length: {len(audio) / rate:.2f} seconds")
wavfile.write("notice.wav", rate, (audio / np.abs(audio).max() * 32767).astype(np.int16))
print("Saved notice.wav")
Output
Characters in: 59 | tokens: 117
Sample rate: 16000 Hz | samples: 60,928 | length: 3.81 seconds
Saved notice.wav

Explanation:

  • The tokenizer works on characters, not words. It puts a blank token between every two characters, so the 59 characters become 117 tokens.
  • VitsModel turns the tokens directly into a waveform: 60,928 samples at 16,000 per second, 3.81 seconds of speech. It decides how long each sound lasts, which is why the length isn't fixed by the text.
  • The model adds a little randomness to the speaking rhythm so the voice sounds natural; torch.manual_seed(0) makes the result the same every run.
  • notice.wav plays in any audio player. Listen to it before the next example.

Example: Speech to Text

This program uses Whisper tiny, an open speech recognition model from OpenAI (Apache 2.0 license on its model card), to transcribe notice.wav. Then it adds louder and louder hiss to see how the transcript holds up, measured by word error rate (WER): the number of words that must be swapped, added or removed to fix the transcript, divided by the number of words actually spoken.

Text to sound to text again, and what noise does to it
Python
import numpy as np
from scipy.io import wavfile
from transformers import pipeline
 
# Whisper tiny (English): a speech-to-text model from OpenAI, 39 million parameters, Apache 2.0 license
asr = pipeline("automatic-speech-recognition", model="openai/whisper-tiny.en")
 
rate, samples = wavfile.read("notice.wav")            # the speech made in the previous program
audio = samples.astype(np.float32) / 32768           # back to values between -1 and 1
 
features = asr.feature_extractor(audio, sampling_rate=rate, return_tensors="np")
print("Log-Mel spectrogram the model reads:", features["input_features"].shape[1:])
 
def word_error_rate(reference, heard):
    ref = reference.lower().replace(".", "").replace(",", "").split()
    hyp = heard.lower().replace(".", "").replace(",", "").split()
    d = list(range(len(hyp) + 1))                     # edit distance between word lists
    for i, r in enumerate(ref, 1):
        prev, d[0] = d[0], i
        for j, h in enumerate(hyp, 1):
            prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (r != h))
    return d[-1] / len(ref)
 
truth = "The science fair is on Friday at ten in the school library."
rng = np.random.default_rng(0)
for noise in [0.0, 0.05, 0.2, 0.5]:                   # add hiss, from none to very loud
    noisy = audio + noise * rng.standard_normal(len(audio)).astype(np.float32)
    text = asr({"raw": noisy, "sampling_rate": rate})["text"].strip()
    shown = text if len(text) < 60 else text[:57] + "..."
    print(f"noise {noise:4}: WER {word_error_rate(truth, text):7.1%}  {len(text.split()):3} words  \"{shown}\"")
Output
Log-Mel spectrogram the model reads: (80, 3000)
noise  0.0: WER   16.7%   12 words  "The Shin's Fair is on Friday at 10 in the school library."
noise 0.05: WER   33.3%   13 words  "The Shin's Fair is on Friday at 10 in the school to break."
noise  0.2: WER   66.7%   11 words  "It's just fair that on Friday, there's ten and a two-diver."
noise  0.5: WER 2483.3%  298 words  "If you're afraid you're afraid you're afraid you're afrai..."

Explanation:

  • The pipeline loads Whisper and its feature extractor, which turns the audio into a log-Mel spectrogram of 80 frequency bands by 3,000 time steps. Whisper always works on 30-second windows, so the 3.81 seconds are padded with silence.
  • The word error rate function counts the fewest word swaps, additions and removals that turn the transcript into the true sentence, a calculation called edit distance.
  • With no noise, WER is 16.7%: 2 of 12 words differ. "Science" was heard as "Shin's", and "ten" was written as "10". The second is not really a mistake, which is why real evaluations normalize numbers before comparing.
  • With light hiss (0.05), "library" became "to break": 33.3%. With heavy hiss (0.2), two thirds of the words are wrong.
  • With very loud hiss (0.5), Whisper hallucinates: it writes 298 words, "you're afraid" over and over, for a sentence of 12. The WER of 2,483.3% is above 100% because every extra word counts as an error.

Choosing and Using Speech Models

Model or serviceKindNotes
Whisper (tiny to large)Open speech-to-textTiny is 39 million parameters; larger versions are much more accurate; supports many languages
MMSOpen speech-to-text and text-to-speechFrom Meta; covers over 1,000 languages
Cloud speech APIsPaid servicesFrom the major cloud providers; add live streaming, speaker labels and many voices
Phone and computer built-insOn-deviceDictation and screen readers that work without sending audio away

The tiny model used here was chosen because it is small and fast. A larger Whisper model, or a cleaner recording, would make far fewer mistakes than the 16.7% here, and a real human voice is different again from a synthetic one. Always measure on audio like your own.

Common Mistakes

Using the wrong sample rate. A model trained on 16 kHz audio gets confused by 44.1 kHz audio passed in as if it were 16 kHz. Resample first, and pass sampling_rate.

Judging by one clear recording. Test with real background noise, accents, microphones and speakers.

Comparing transcripts character by character. Use word error rate, after normalizing case, punctuation and numbers.

Cloning or recording voices without consent. A voice is personal data. Record and copy voices only with permission; see "Privacy: What Not to Share with AI".

Interview Corner

How does a modern speech recognizer like Whisper work?

It turns audio into a log-Mel spectrogram, encodes it with a Transformer encoder, and a decoder writes the text one token at a time. It is trained on hundreds of thousands of hours of audio paired with transcripts.

What is word error rate?

The number of word substitutions, insertions and deletions needed to turn the transcript into the correct text, divided by the number of correct words. Lower is better, and it can go above 100% when the model adds many extra words.

Practice

Exercise: your own announcement. Change the text in the text-to-speech program to a sentence of your own with a number, a date and a name, then transcribe it. Which words does Whisper get wrong? Does openai/whisper-base.en, a larger model, do better?

Check your understanding:

  1. How many samples are in 3.81 seconds of audio at 16 kHz?
  2. What does a spectrogram show?
  3. Why can word error rate be more than 100%?

Quick check: speech AI

4 questions
1What sample rate do most speech models use?
2What was the word error rate with no added noise?
3What did Whisper do with very loud noise?
4What does a text-to-speech model produce?

Key Takeaways

Quick reference

NeedCode
Read or write a WAV filewavfile.read(path), wavfile.write(path, rate, samples)
Speech-to-textpipeline("automatic-speech-recognition", model="openai/whisper-tiny.en")
Transcribe audio samplesasr({"raw": audio, "sampling_rate": rate})["text"]
Text-to-speechVitsModel.from_pretrained("facebook/mms-tts-eng")(**tokenizer(text, return_tensors="pt")).waveform
Frequencies in a soundnp.fft.rfft(samples)

Was this tutorial helpful?

Lesson 143 of 186