Speech and Audio: TTS, STT and Generation
Two directions, two different problems
Speech work splits into a clean pair of tasks that share a medium and almost nothing else. Text-to-speech must invent everything a recording contains â timing, emphasis, breath, the exact pitch contour that makes a sentence sound like a question â from a string of characters with no prosody in it at all. Speech-to-text must undo that invention: recover the words from a signal that has been coloured by a microphone, a room, an accent, a cough, and two people talking over each other. One problem is generative and judged on how natural the output feels; the other is discriminative and judged on how few words it gets wrong.
Between them sits the audio representation question, which decides almost everything about quality. Raw waveforms give maximum fidelity and enormous sequences; mel spectrograms compress the signal into something closer to how ears resolve frequency, and most systems work there, converting to a waveform only at the last stage. The component that performs that final conversion â the vocoder â is often what separates speech that sounds like a person from speech that sounds like a person recorded through a tin can.
Text to speech in three stages
A modern pipeline reads text, predicts an intermediate acoustic representation, and turns that representation into sound. Text normalisation handles the awkward cases: converting digits, expanding abbreviations, and deciding whether "Dr" is a title or a unit of weight. The acoustic model then predicts the spectrogram or latent frames conditioned on the normalised text, often with a speaker embedding so the same words can be spoken in different voices. Finally the vocoder renders those frames into a waveform at the sample rate your player expects.
from transformers import pipeline
import numpy as np
import soundfile as sf
def text_to_speech(text, model="facebook/mms-tts-eng", out="speech.wav"):
tts = pipeline("text-to-speech", model=model)
result = tts(text)
audio = np.asarray(result["audio"], dtype=np.float32)
sf.write(out, audio, samplerate=result["sampling_rate"])
return out, result["sampling_rate"]
def clone_voice(text, voice_samples, preset="fast"):
"""Voice cloning: condition on reference recordings of a speaker."""
from tortoise.api import TextToSpeaker
tts = TextToSpeaker()
return tts.tts_with_preset(text, voice_samples=voice_samples, preset=preset)
Two settings dominate the quality conversation. The sample rate decides apparent fidelity: sixteen kilohertz is fine for telephony, while speech that should pass as a studio recording wants at least twenty-four. And the preset or step count in diffusion-style TTS systems trades latency against naturalness, the same trade-off as image samplers â worth fixing once you know your interaction budget.
Speech to text in practice
Transcription looks solved until you feed it real recordings. Clean studio audio with a single speaker is easy; a meeting room with four participants, crosstalk, and an air conditioner is where systems earn their reputation.
import whisper
def speech_to_text(audio_path, model_size="base", language=None):
model = whisper.load_model(model_size)
result = model.transcribe(audio_path, language=language,
word_timestamps=True)
return {
"text": result["text"],
"language": result["language"],
"segments": [
{"start": s["start"], "end": s["end"], "text": s["text"]}
for s in result["segments"]
],
}
Model size is a real lever: a large model on a laptop may be perfectly usable and dramatically better than a small one on noisy input, and the runtime cost is usually acceptable for offline jobs. Passing the language explicitly removes misdetection on short clips â a five-second sample often gets identified as the wrong language entirely â and word-level timestamps are what you need for captions, search, and alignment against a transcript, so request them up front rather than trying to reconstruct them later.
Beyond words: music and sound effects
Non-speech audio generation follows the same pattern as text and images â condition a generative model on a description, sample until something works â but evaluation is harder because there is no reference transcript to compare against. Music models generate from prompts describing genre, instrumentation, and mood; sound effect models fill in interface sounds, footsteps, and ambience. The honest limitation is structure: models produce convincing textures and short motifs, but sustained harmonic development over minutes remains unreliable, and loops drift out of key.
| Task | Conditioning | Typical output | Main weakness |
|---|---|---|---|
| TTS | Text, speaker reference | Mono speech | Emotion, unusual names |
| Voice conversion | Speech, target speaker | Speech in new voice | Latency, artefacts |
| Music generation | Genre, instruments, mood | Stereo track | Long-form structure |
| Sound effects | Short description | Short clip | Precision of timing |
| Enhancement | Noisy speech | Clean speech | Over-smoothing speech |
Evaluating audio honestly
Word error rate is the headline metric for transcription and it hides as much as it reveals: a system can score well overall while failing systematically on names, numbers, and accented speakers, which are precisely the errors users notice. Slice your evaluation set by domain, by noise level, and by speaker group, and read the slices rather than the aggregate.
For synthesis, three axes matter and they pull against each other. Intelligibility: does a listener or an automatic speech recognition pass recover every word? Speaker similarity: does the voice match the reference, measured with a speaker embedding cosine similarity, and does it stay stable across sentences? Naturalness: mean opinion scores from listeners, or a learned predictor as a cheap proxy. Latency belongs on the same dashboard â time to first audio is what determines whether an assistant feels responsive, and a model that sounds perfect after two seconds of silence loses to one that starts immediately and sounds slightly worse.
Chunking interacts with all of these. Long passages synthesised in one call drift: the voice drifts, the pace flattens, and a single mispronounced name forces you to regenerate everything. Synthesising sentence by sentence keeps quality local and lets you cache finished chunks, at the cost of prosodic continuity across boundaries â joins where the pitch does not carry over. The usual compromise is paragraph-level synthesis with a fixed seed and a short crossfade, which keeps most of the natural phrasing while limiting how much one bad sentence costs you.
Consent, safety and deployment
Voice is an identity document. A few seconds of recording is enough for modern systems to produce a convincing impersonation, which makes consent the first deployment question rather than the last. Collect speaker references with explicit permission, scope the licence to the intended use, and keep a record of who authorised what. Systems that clone arbitrary voices from arbitrary samples have a different risk profile from systems that only use licensed voices, and your architecture should reflect which one you have built.
Watermarking and provenance metadata help, but they are defeatable, so treat them as evidence rather than as prevention. The controls that actually hold up are operational: restrict who can submit reference audio, log every generation with the speaker and requester, rate-limit by account, and monitor for the impersonation patterns your support team will hear about first. For transcription, the parallel concerns are retention and access â audio recordings are sensitive by default, so transcribe at the edge where you can, delete raw audio when the transcript suffices, and keep the transcript under the same access controls as the conversation it came from.
Common Mistakes
Judging transcription on aggregate word error rate alone
Fix: Slice by noise, accent, and domain; names and numbers are where users actually notice failures.
Treating voice cloning as a neutral feature
Fix: Obtain and record speaker consent, scope it to a use, and keep an auditable authorisation trail.
Choosing a TTS model on naturalness while ignoring time to first audio
Fix: Measure latency alongside quality; responsiveness dominates polish in conversational products.
Letting raw audio sit in storage after transcription
Fix: Delete or encrypt recordings once the transcript exists, and apply the transcript's access controls from the start.
Best Practices
- Pin the sample rate and channel layout at the boundary of your system so downstream files never disagree.
- Request word-level timestamps when transcribing; captions and search both need them later.
- Keep a fixed evaluation set of hard recordings â noise, crosstalk, accents â and run it on every model upgrade.
- Separate speaker libraries from generation endpoints so consent checks live in one place.
Key Takeaways
- TTS invents prosody from text while STT recovers words from a degraded signal; they fail in different ways.
- Normalisation, acoustic modelling, and vocoding are the three TTS stages where quality is decided.
- Transcription degrades with noise, crosstalk, and short clips; explicit language hints and larger models recover much of it.
- Evaluate synthesis on intelligibility, speaker similarity, naturalness, and latency together, not on naturalness alone.
- Voice is identity: consent, authorisation records, and access logging are part of the architecture, not paperwork.