Start with an example: A recording is not yet a transcript
Imagine recording a two-minute classroom discussion. To a listener, it contains words, different speakers, pauses, and background noise. To a computer, the recording initially contains samples of an audio waveform: numerical measurements changing over time.
Different AI tasks ask different questions about those samples. Automatic speech recognition tries to recover words. Speaker diarization asks who spoke when. Audio classification may identify a door closing or a vehicle passing. Text-to-speech runs in the other direction, producing audio from written text.
Because these tasks have different goals, they are evaluated differently. A transcript may have low word error yet attribute a sentence to the wrong speaker. A system may recognize sounds correctly in a quiet room and fail in a noisy street. Studying representations and evaluation is as important as studying model architectures.
Sound carries information about language, speakers, environments, and events. Speech and audio AI refers to computational methods for analyzing, interpreting, transforming, or generating sound. These systems can transcribe a lecture, produce spoken directions, identify an acoustic event, separate speakers in a meeting, or suppress noise in a recording.
Speech AI concentrates on spoken language and speakers. Audio AI is broader: it also includes music, environmental sounds, machinery, and other non-speech signals. Different applications use different outputs, so recognizing words, recognizing a speaker, and classifying a sound are separate problems.
1. How computers represent sound
Sound is a physical pressure wave. A microphone converts pressure variations into an electrical signal; an analog-to-digital converter samples the signal and stores numerical values. The resulting waveform records amplitude over time.
Three properties matter:
- Sample rate: Measurements collected per second, expressed in hertz (Hz). A sample rate of 16,000 Hz means 16,000 samples per second, per channel.
- Bit depth: Number of bits used to represent each sample in a conventional pulse-code modulation (PCM) recording; it influences quantization precision and dynamic range.
- Channels: Separate streams of samples, such as mono (one channel) or stereo (two channels).
For an uncompressed mono PCM recording, the approximate data size in bits is:
For example, 10 seconds at 16,000 samples per second and 16 bits per sample requires 2,560,000 bits, or 320,000 bytes, before file headers. Stereo at the same settings requires approximately twice as much.
Higher sample rates can preserve higher-frequency content, but increasing the sample rate does not recover frequencies missing from an existing recording. According to the sampling theorem, a band-limited signal must be sampled at a rate greater than twice its highest frequency for ideal reconstruction under the theorem’s assumptions.
Waveforms and spectrograms
A waveform shows amplitude over time. It is useful for observing silence, clipping, duration, and broad signal characteristics. A spectrogram shows how frequency content changes with time, making it easier to observe speech harmonics, vowels, noise, and acoustic events.
The short-time Fourier transform (STFT) divides the waveform into overlapping frames, analyzes each frame’s frequency content, and produces a time-frequency representation. A common visualization converts spectral magnitudes to a decibel scale. Mel spectrograms apply a perceptually motivated frequency scale and are widely used as model inputs.
2. The main speech and audio AI tasks
| Task | Input | Typical output | Example |
|---|---|---|---|
| Automatic speech recognition (ASR) | Spoken audio | Written transcription | Lecture captions |
| Text-to-speech (TTS) | Text, possibly voice controls | Speech waveform | Spoken navigation |
| Speech translation | Speech in one language | Text or speech in another language | Multilingual interpreting |
| Speaker identification | Speech plus known enrolled identities | Speaker identity | Recognizing an authorized speaker |
| Speaker verification | Speech and a claimed identity | Match score or decision | Checking a voice claim |
| Speaker diarization | Multi-speaker recording | Who spoke when, with anonymous speaker labels | Meeting transcript |
| Audio classification | Audio segment | Category label | Detecting a siren |
| Sound event detection | Recording | Event labels and time intervals | Locating alarms in time |
| Speech enhancement | Noisy or distorted speech | Cleaner speech estimate | Improving call audio |
| Source separation | Mixture of sounds | Separate estimated signals | Separating speech from background sound |
A single product may combine several tasks, but they should be measured separately. A meeting assistant, for example, may use diarization to find speaker turns and ASR to recover the spoken words.
3. Automatic speech recognition (ASR)
Automatic speech recognition converts spoken language into a sequence of words or other text units. The system must account for variation in speakers, accents, speaking rate, microphone quality, and background noise.
A typical ASR workflow is:
- Capture an audio waveform and check its sample rate and channel count.
- Normalize or resample audio to match the model’s input requirements.
- Convert the waveform into a representation the model accepts, such as features or waveform tokens.
- Use the recognition model to predict speech units, tokens, or text.
- Decode predictions into readable text; optionally add punctuation, timestamps, or speaker labels.
Some recognizers predict text using an acoustic model and a separate language model; modern end-to-end systems can learn much of this process jointly. Common approaches include CTC-based models, encoder-decoder models, and transducer architectures.
Connectionist Temporal Classification (CTC) is a training objective that lets a model learn from audio and transcript pairs without manually assigning each transcript token to a precise audio frame. Sequence-to-sequence attention models instead learn to map an audio representation to output tokens, often autoregressively.
Example: captions from a lecture
Imagine a 30-minute lecture. The recognizer processes the recording, predicts the words, and returns a transcript. For usable captions, the application also needs timestamps, text segmentation, and possibly punctuation. If the lecturer switches languages, recognition quality depends on the model’s language coverage and the evaluation dataset.
ASR provides predicted text, not a guarantee of what was said. Proper names, technical terminology, and quiet speech are particularly vulnerable to errors.
4. Text-to-speech (TTS)
Text-to-speech synthesizes audio corresponding to written text. A TTS system often needs to decide how words should be pronounced, model speech rhythm and intonation, and generate a waveform.
Possible stages include:
- Text normalization: Expand abbreviations, numbers, and other symbols into a form suitable for speaking.
- Linguistic representation: Convert written words into suitable tokens, phonemes, or contextual representations.
- Acoustic generation: Predict a speech representation, such as acoustic features or audio tokens.
- Waveform synthesis: Generate the final sound, sometimes using a vocoder.
Not every modern TTS architecture uses these as separate modules. Some models generate audio tokens directly and decode them to a waveform.
A vocoder converts an acoustic representation into sound. Older systems often relied on explicit signal-processing vocoders; neural vocoders use learned models. TTS quality depends on intelligibility, naturalness, expressiveness, latency, and pronunciation accuracy.
A speech synthesizer may produce fluent-sounding audio while pronouncing uncommon names or technical symbols incorrectly. Applications should test pronunciation using their own domain-specific vocabulary.
5. Speaker recognition and diarization
These are easily confused and serve different objectives.
Speaker identification asks: Which enrolled person is speaking? It compares the voice to a set of known candidates.
Speaker verification asks: Does this voice match the claimed speaker? It produces a similarity score or decision, often using learned voice embeddings.
Speaker diarization asks: Who spoke when? It segments a recording by speaker without necessarily knowing anyone’s real identity. Output labels might be SPEAKER_00 and SPEAKER_01.
Voice characteristics change with microphones, health, room conditions, emotion, and noise. Verification is not infallible, and synthetic voices or replay attacks can pose security risks. Speaker systems also raise privacy and consent concerns because voice can be identifying personal information.
How diarization is typically performed
One pipeline detects speech activity, extracts representations from short speech segments, groups similar segments into speaker clusters, and refines boundaries. Modern neural systems can also predict speaker activity directly. Overlapping speech is a particularly difficult case.
Diarization and transcription solve complementary problems. Neither automatically proves a speaker’s real-world identity.
6. Non-speech audio understanding
Audio models can recognize sounds such as footsteps, rainfall, glass breaking, or equipment faults. This task may be audio classification, in which one label represents an entire clip, or sound event detection, in which each event is located within a recording.
For example, an industrial monitoring system may classify a five-second motor recording as normal or abnormal. A more detailed system may also locate the start and end of a rattling noise. Whether such a system works in a factory depends on real recordings from its machines, microphones, and noise conditions.
An important distinction is between anomaly detection and fault diagnosis. An unusual sound can indicate that a recording differs from the expected pattern, but it does not by itself prove a specific mechanical failure.
7. How audio models learn
Different audio architectures handle the time dimension in different ways:
- Convolutional neural networks (CNNs) learn local patterns, often in spectrograms or waveform features.
- Recurrent neural networks (RNNs) process sequences while carrying state across steps.
- Transformers use attention to model relationships across audio frames or tokens.
- Self-supervised audio encoders learn representations from audio without requiring a transcript or label for every training example.
- Generative audio models learn to produce waveforms, acoustic features, or discrete audio tokens.
Training data must match the task. ASR often uses audio-transcript pairs, audio classification uses clip labels, and speaker verification uses voice recordings with speaker identity annotations. Self-supervised pretraining can improve representations before task-specific adaptation.
Training is distinct from inference: training changes learned parameters using examples; inference uses those parameters to predict outputs from new audio. See AI Systems, Models, Training, and Inference.
8. Preparing audio datasets
Raw recordings often need careful handling before they can be used reliably:
- Format and decoding: Confirm that files can be read and that channel and sample-rate metadata is accurate.
- Resampling: Convert sample rates correctly rather than merely changing the metadata.
- Channel handling: Mix channels only when appropriate; careless mixing can cancel parts of a signal.
- Trimming and segmentation: Define recording boundaries and account for silence without deleting meaningful speech.
- Loudness and clipping: Identify distortion and amplitude differences that may affect learning.
- Annotation quality: Check transcripts, speaker labels, and event timestamps.
- Data splitting: Separate train, validation, and test examples without leaking speakers, sessions, locations, or near-duplicate recordings when those groups affect deployment.
Why dataset leakage is dangerous
Suppose recordings from the same speaker and microphone appear in both training and testing. A model may score highly by exploiting recurring voice or recording characteristics rather than generalizing to new speakers or settings. A speaker-independent test split may provide a more meaningful evaluation for a product intended to work with previously unseen people.
The correct split depends on the deployment goal. See Data Splitting, Labeling, and Leakage.
9. Practical Python: inspecting a waveform and its spectrum
The following self-contained NumPy example generates a two-tone signal, measures its duration, computes a Fourier spectrum, and identifies its strongest frequency peaks. It demonstrates signal representation without requiring a microphone, model download, or network connection.
import numpy as np
sample_rate = 16_000
seconds = 1.0
t = np.arange(int(sample_rate * seconds)) / sample_rate
# Two synthetic tones: 440 Hz and 880 Hz.
audio = (
0.7 * np.sin(2 * np.pi * 440 * t)
+ 0.3 * np.sin(2 * np.pi * 880 * t)
).astype(np.float32)
assert audio.ndim == 1
print("Sample rate:", sample_rate, "Hz")
print("Duration:", len(audio) / sample_rate, "seconds")
print("Peak amplitude:", round(float(np.max(np.abs(audio))), 3))
# Real-valued FFT for nonnegative frequency bins.
spectrum = np.abs(np.fft.rfft(audio))
frequencies = np.fft.rfftfreq(len(audio), d=1 / sample_rate)
# The strongest bins approximate the frequencies of the two tones.
strongest = np.argsort(spectrum)[-2:]
print("Strongest frequencies (Hz):", sorted(frequencies[strongest].tolist()))
Expected frequency output is approximately [440.0, 880.0]. The numerical values illustrate how a waveform encodes frequencies. Real speech contains time-varying patterns, and an FFT across an entire recording loses information about when each sound occurs. For that reason, speech systems frequently use short-time features or representations learned directly from samples.
Practical model integration
For actual ASR or TTS, choose a documented model and check its required sample rate, audio encoding, accepted languages, licensing, and runtime requirements. Model APIs and pretrained systems differ significantly, so a generic snippet that assumes one universal input shape would be misleading.
The broader implementation principles are covered in Deep Learning with PyTorch and AI Development Tools.
10. Evaluating speech and audio systems
A useful metric depends on the task. Different metrics measure different kinds of error.
| Task | Common measures | What they assess |
|---|---|---|
| ASR | Word error rate (WER), character error rate (CER) | Insertions, deletions, and substitutions relative to a reference transcript |
| TTS | Listening tests, mean opinion score (MOS), intelligibility checks | Perceived naturalness and whether speech can be understood |
| Speaker verification | Equal error rate (EER), false acceptance/rejection rates | Authentication trade-offs at different thresholds |
| Diarization | Diarization error rate (DER) | Missed speech, false alarms, and speaker confusion |
| Audio classification | Precision, recall, F1-score, confusion matrix | Label prediction quality |
| Event detection | Event-based precision and recall, onset/offset error | Whether events and their time ranges are detected |
| Enhancement | Perceptual quality and intelligibility measures | How the processed audio is perceived and understood |
Word error rate
Word error rate counts substitutions, deletions, and insertions against a reference transcript:
Here, is substitutions, is deletions, is insertions, and is the number of words in the reference. For a reference of 20 words with 2 substitutions, 1 deletion, and 1 insertion, WER is , or 20%. WER can exceed 100% when enough insertions occur.
WER is sensitive to tokenization and text normalization. For a fair comparison, specify whether punctuation, case, numerals, and spelling variants are normalized. WER also says little about whether the transcription error changes the meaning of a safety-critical instruction.
Beyond model accuracy
Real deployments must also measure latency, processing cost, memory, energy use, robustness across speakers and environments, privacy impact, and accessibility. A system that transcribes accurately in a quiet lab may fail outdoors or under poor connectivity.
11. Real-time versus batch processing
Batch processing analyzes a complete recording after it is available. Examples include offline transcription of meetings or indexing an audio archive.
Streaming processing handles incoming audio incrementally and may emit partial results before the speaker finishes. This is important for live captions and voice interaction, but it introduces trade-offs between delay, context, and prediction stability.
For streaming recognition, distinguish:
- Latency: Time between hearing a sound and producing a usable result.
- Throughput: Amount of audio processed per unit of computation time.
- Partial hypothesis: A provisional transcript that may change as more speech arrives.
- Endpoint detection: Deciding when a speaker has paused or finished an utterance.
A model’s ability to process a prerecorded clip quickly does not automatically mean it supports low-latency live conversation.
12. Limitations, safety, and responsible deployment
Noise and domain shift
Wind, reverberation, simultaneous speakers, unfamiliar accents, and recording devices can degrade performance. Evaluate using data that resembles the intended setting, not only clean benchmark recordings.
Language and accent coverage
Language support is uneven. Results for a widely represented language or accent may not transfer to another language, dialect, or code-switched conversation. Test relevant communities and domain vocabulary directly.
Privacy and consent
A voice recording may contain identifiable voices, private conversations, or sensitive information. Collect only what is necessary, obtain appropriate consent or other lawful authorization, define retention limits, secure stored audio, and minimize access.
Spoofing and synthetic speech
Generated or replayed audio can imitate a person’s voice. Voice similarity alone should not be treated as strong proof of identity, particularly for high-risk authentication or financial decisions.
Errors with real consequences
Misrecognized drug names, addresses, technical commands, or emergency instructions can cause harm. Sensitive workflows need confidence checks, error correction, and human verification where appropriate.
13. How this topic connects to the AI knowledge map
Speech and audio AI combines the signal-processing foundations introduced here with Neural Network Fundamentals, Convolutional and Recurrent Neural Networks, and Training Neural Networks. The same sequential modeling ideas also appear in Natural Language Processing Fundamentals and Text Processing, Tokenization, and Embeddings.
Speech generation relates to Generative AI and Generative Model Families, while modern audio-language systems connect to The Transformer Architecture and Multimodal Artificial Intelligence. These later pages are part of the planned PlainCS knowledge map.
14. Check your understanding
- Why does changing a file’s sample-rate label not correctly resample the waveform?
- What information can a spectrogram reveal that a single full-recording Fourier spectrum cannot?
- How does diarization differ from identifying a speaker by name?
- Why might a low WER still be unacceptable in a medical transcription workflow?
- When would an application need streaming ASR rather than batch recognition?
- Why should an audio classification dataset be split by recording session or device in some applications?
References and further reading
- Stanford CS224S: Spoken Language Processing — speech technology, recognition, and generation.
- Torchaudio documentation — audio processing and model workflows in the PyTorch ecosystem.
- Librosa documentation — Python tools for audio analysis and feature extraction.
- Hugging Face Audio Course — practical audio machine learning and speech tasks.
- NIST Speaker Recognition Evaluations — speaker recognition evaluation context.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.