Audio signals: amplitude, channels and PCM
音频信号基础
Compute finite-waveform RMS, expose phase cancellation and saturation, and write verified PCM16 WAV bytes.
audio-signalsHow can two active channels average to silence?
Synthesize a sine with amplitude 0.5 and put it in the left channel. Put its negative in the right channel. Each channel has nonzero root-mean-square amplitude, yet their samplewise average is identically zero. This reproducible phase-inversion example shows why digital audio stores signed values through time: one “volume” number cannot replace a waveform.
Audio processing starts by interpreting those numbers correctly. The sample rate counts samples per second per channel. A frame contains all channel values at one sampling instant. A 64-frame stereo recording at 8,000 Hz has 64 samples per channel, 128 numbers in total, and a nominal duration of 8 ms. Its last sample is at 63/8000 seconds; an evenly spaced array that includes the 8 ms endpoint would use the wrong sample times.
Sampling and quantization answer different questions: when to measure, and which numbers can represent the result. This article covers digital amplitude, statistics and pulse-code modulation (PCM). Frequency aliasing belongs to the sampling topic. Chapter 3 of the DSP Guide discusses these as separate steps. Sampling and quantization
Set the units before computing energy
Let be the digital amplitude in channel at frame . The per-channel sample rate is in hertz, and is the frame count. Amplitude here is dimensionless relative to a reference value of 1, not measured in pascals; physical sound pressure requires device calibration.
Temporarily omit the channel index. The mean captures a DC offset, peak is the largest absolute amplitude, and root mean square (RMS) measures average squared amplitude through its square root. Discrete energy here is a sum of squares, not acoustic energy in joules. Across records of different lengths, it is not a direct measure of average intensity. Statistics and RMS
Write each sample as . Expanding its square and summing makes the cross term vanish, giving:
Here uses denominator to describe this finite record. Replacing it with the denominator often used to estimate population variance would invalidate the same identity. Chapter 2 of the DSP Guide uses in its sample-variance equation; this article deliberately chooses a different convention for finite waveforms. The variance convention
A 64-sample, 500 Hz sine of amplitude 0.5 at 8 kHz contains exactly 4 cycles. Its mean is approximately 0, peak 0.5, , , and . Adding 0.2 to every sample leaves the variance unchanged but raises RMS to . RMS includes DC.
Decibels express a logarithmic ratio. This example takes RMS amplitude 1 as its 0 dBFS reference. Mathematical silence is negative infinity; JSON represents it with null and a separate silence flag:
This is neither sound-pressure level in dB SPL nor a perceptual loudness measure. A display referenced to the RMS of a peak-one sine would give a different number, so reports should specify both the statistic and the reference. Ideal amplitude doubling adds about 6.0206 dB; clipping invalidates that ideal gain relationship.
A signed -bit PCM grid contains integer codes. We resolve midpoint ties by rounding to the nearest even integer, limit the integer range, then convert the data type:
If rounding does not saturate, the nearest grid point is at most half a step away. The positive endpoint 1 cannot be represented exactly: PCM16 outputs 32767/32768, a full-step error. Amplitude 1.5 incurs an error near 0.5: clipping, not a tiny quantization discrepancy. The DSP Guide’s uniform-noise approximation has conditions; a fixed constant’s deterministic rounding error is not automatically independent white noise. Quantization error
Write actual WAV bytes from an array
The complete program uses Python 3.12, NumPy 1.26.4 and the standard-library wave module. One-dimensional input becomes mono; two-dimensional input is frames by channels. Teaching bounds are 1–16,000 frames, 1–2 channels, and finite amplitudes within ±8. Values beyond the PCM range are allowed to demonstrate clipping, not to promise lossless encoding.
"""Bounded digital audio statistics, signed quantization and PCM16 WAV encoding.
RMS dBFS uses amplitude reference 1. It is not calibrated sound-pressure level.
"""
import io
import json
import wave
import numpy as np
def signal(values):
raw=np.asarray(values)
if np.iscomplexobj(raw):raise ValueError('Real audio is required')
x=np.asarray(raw,dtype=float)
if x.ndim==1:x=x[:,None]
if x.ndim!=2 or not 1<=len(x)<=16000 or not 1<=x.shape[1]<=2 or not np.isfinite(x).all() or np.max(np.abs(x))>8:
raise ValueError('Use 1–16000 frames, 1–2 channels and finite amplitude within ±8')
return x.copy()
def stats(values):
x=signal(values);mean=x.mean(axis=0);rms=np.sqrt(np.mean(x*x,axis=0));variance=np.mean((x-mean)**2,axis=0)
return dict(frames=len(x),channels=x.shape[1],mean=mean.tolist(),population_variance=variance.tolist(),
rms=rms.tolist(),peak=np.max(np.abs(x),axis=0).tolist(),energy=np.sum(x*x,axis=0).tolist(),
rms_dbfs=[float(20*np.log10(v)) if v>0 else None for v in rms],silence=(rms==0).tolist())
def quantize(values,bits=16):
x=signal(values)
if type(bits) is not int or not 2<=bits<=16:raise ValueError('Bits must be 2–16')
scale=2**(bits-1);rounded=np.rint(x*scale);q=np.clip(rounded,-scale,scale-1).astype(np.int64);decoded=q/scale
return dict(bits=bits,step=1/scale,integers=q.tolist(),decoded=decoded.tolist(),
saturated=int(np.count_nonzero(rounded!=q)),max_error=float(np.max(np.abs(decoded-x))),
mse=float(np.mean((decoded-x)**2)),rounding='nearest with ties to even; signed grid, clipping before integer conversion')
def pcm16(values,rate=8000):
if type(rate) is not int or not 1<=rate<=48000:raise ValueError('Rate must be 1–48000 samples/second')
x=signal(values);q=np.asarray(quantize(x,16)['integers'],dtype='<i2');buffer=io.BytesIO()
with wave.open(buffer,'wb') as writer:
writer.setnchannels(x.shape[1]);writer.setsampwidth(2);writer.setframerate(rate);writer.writeframes(q.tobytes(order='C'))
return buffer.getvalue()
def demo():
rate=8000;x=.5*np.sin(2*np.pi*500*np.arange(64)/rate);stereo=np.column_stack([x,-x]);data=pcm16(stereo,rate)
with wave.open(io.BytesIO(data),'rb') as reader:header=dict(channels=reader.getnchannels(),sample_width=reader.getsampwidth(),rate=reader.getframerate(),frames=reader.getnframes())
return dict(rate=rate,frequency=500,samples=x.tolist(),tone=stats(x),offset=stats(x+.2),
stereo=stats(stereo),mono_average=stats(stereo.mean(axis=1)),quant8=quantize(x,8),
clipping=quantize(3*x,16),endpoint=quantize([-1.,1.],16),wav=dict(bytes=len(data),header=header),
silence=stats(np.zeros(8)))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
pcm16 writes little-endian signed 16-bit integers. Left and right values within a frame are adjacent, followed by the next frame. The pinned SciPy documentation describes the array layout and type ranges, including unsigned integers for 8-bit WAV. Our mathematical signed 8-bit quantizer is not the 8-bit WAV file format. WAV types and channels
The 64-frame stereo PCM16 file actually contains 300 bytes: the 44-byte header generated by this program plus 256 bytes of sample data. Other WAV files can contain extra metadata chunks; subtracting 44 from file size is not a general WAV parser. The program reopens its header to check channels, sample rate, sample width and frame count. Statistics, quantization and encoding take time and returned storage.
Predict before editing demo: replacing the right channel’s -x with x should move the averaged RMS from 0 to the original channel’s RMS. Multiplying the sine by 3 raises saturation count and maximum error. This uses synthetic arrays and real format encoding, without a microphone recording or a listening study.
What one RMS number cannot tell you
Equal-RMS signals can have different peaks, frequency contents and temporal structures. Two individually valid channels can cancel when mixed. Speech-data inspection should therefore include channel layout, duration, silent segments, clipping and waveforms, rather than accepting files solely by average amplitude.
Converting to floating point cannot recover detail already lost to quantization. Changing a header’s sample rate is not resampling. Whether to remove DC, apply automatic gain or normalize depends on the task; normalizing every segment separately may erase meaningful intensity differences. This program does not implement compressed codecs, perceptual loudness or device calibration. Continue frequency analysis with the Fourier transform.
Check your intuition with short arrays
-
Understanding. How many numbers are in 64stereo frames at 8 kHz, and how long is the recording?
Answer: 128 numbers and a nominal duration of 8 ms. The sample rate applies per channel; stereo does not double the duration to 16 ms.
-
Calculation. Find the mean, population variance, RMS and our dBFS value for[1, −1]. What changes for[2,0]?
Answer: The first has mean 0, variance 1, RMS 1 and 0 dBFS. The second has mean 1, still variance 1, RMS and approximately 3.0103 dBFS. Those floating-point statistics are valid, but the second array cannot be encoded by our PCM16 routine without clipping.
-
Boundary. Why does quantizing 1 to 16bits violate the half-step error bound?
Answer: The nearest integer 32768 exceeds the maximum code 32767 and is clipped. The error is . The half-step bound requires unsaturated nearest rounding.
-
Method choice. Both channels have ordinary RMS values but their mono mix is nearly silent. Should you first increase gain or inspect channel phase and mixing rules?
Answer: Inspect the channel relationship. If one channel is the other’s negative, their average is exactly zero; later amplification cannot recover it. Preserving the channels and investigating the source diagnoses more than blindly amplifying based on a single RMS threshold.
Keep conclusions within the reading scope
DSP Guide chapter 2 supports the statistical definitions; chapter 3 supports sampling, quantization and error conditions. The variance denominator and decibel reference are specified separately here. SciPy 1.15.3 documentation checks WAV layout and types; the program does not call SciPy. Code and numerical examples are original. Finite-array checks do not validate real devices or perceived sound.
Make a prediction, then check
Why can two active stereo channels average to silence?
Learning objectives
- Interpret sample rate, frames, channels and digital units.
- Derive RMS from population variance and DC offset.
- Distinguish unsaturated rounding error from clipping.
- Encode and inspect interleaved PCM16 bytes.
Prerequisites & connections
Explore related knowledge →References
- The Scientist and Engineer’s Guide to DSP, chapter 2: Statistics, Probability and Noise
Steven W. Smith - The Scientist and Engineer’s Guide to DSP, chapter 3: ADC and DAC
Steven W. Smith - SciPy 1.15.3: scipy.io.wavfile.write
SciPy contributors · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked finite digital-audio units, N-denominator variance/RMS identity, explicit reference-one dBFS, unsaturated quantization bounds, positive PCM endpoint saturation and real little-endian stereo WAV encoding against scoped DSP Guide chapters2/3 and SciPy1.15.3 WAV documentation. Six paired equations and four explained exercises. Synthetic arrays and byte checks, not calibrated sound pressure or listening studies.
- Checked RMS/DC arithmetic, −9.030900dBFS reference, stereo cancellation, signed grid ties/endpoints, saturation and actual300-byte WAV header/interleaving.
- Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- The Scientist and Engineer’s Guide to DSP, chapter 2: Statistics, Probability and Noise · Read Mean and Standard Deviation; visually inspected printed page14/equation2-2. The source uses N−1 sample variance; this finite-waveform example explicitly uses N. Current PDF revision year not verified.
- The Scientist and Engineer’s Guide to DSP, chapter 3: ADC and DAC · Read Quantization and Sampling Theorem sections; visually inspected printed page40. Half-step error needs no saturation; the Nyquist equality/phase counterexample is independently derived. Current PDF revision year not verified.
- SciPy 1.15.3: scipy.io.wavfile.write · Read Notes on frames-by-channels shape and signed16/unsigned8-bit ranges. Reference only; our standard-library PCM16 writer is original and SciPy was not executed. Release version predates cutoff.
Related topics