Audio files: WAV
| Problem | Store sampled sound losslessly as PCM or floating-point samples in RIFF/WAVE files, the common exchange format for audio |
| Devised by | Electronic Arts (1985), the IFF chunk format; IBM and Microsoft (1991), RIFF/WAVE |
| Accuracy | WAV files from Python’s wave module and hand-built headers read exactly; SciPy reads the library’s WAV files to within half a quantisation step (tables below) |
| Cost | |
| Read first | Background: sampling and aliasing |
| API | parse_wav, encode_wav, read_wav_file, write_wav_file, WavAudio, WavSampleFormat |
Overview
A WAV file is the plainest way to keep sound: a short header saying how many channels, how many samples per second and how many bits per sample, then the samples themselves, interleaved frame by frame. Nothing is lost, and nothing is saved: CD-quality stereo takes 1411 kbit/s.
Uncompressed PCM is what audio software exchanges and what signal-processing code works on, so WAV is the format the library reads and writes. Compressed formats such as MP3, AAC and FLAC are outside its scope.
Where it is used
WAV is the plain, uncompressed format that audio tools can always read.
- Signal-processing work. Recorded test signals, measurements from sound cards and the output of filters and synthesisers are exchanged as WAV files.
- Audio analysis. Speech and music research, acoustics measurements and machine-learning data sets are stored as PCM or floating-point WAV.
- Hardware. Samples from an oscilloscope or software-defined radio are often saved as WAV for quick inspection in standard tools.
History
The RIFF container and its WAVE form were defined by IBM and Microsoft in 1991 for Windows multimedia. Later extensions added a “WAVE_FORMAT_EXTENSIBLE” header for more channels and sample formats. RIFF itself followed Electronic Arts’ Interchange File Format (1985), which introduced the idea of a file as a sequence of tagged, length-prefixed chunks that a reader can skip if it does not understand them. That design is why WAV files survive the metadata chunks that recorders and editors add.
The idea
WAV files
A WAV file is a list of chunks, each with a four-character identifier and a length. The fmt chunk gives the sample format (integer PCM or IEEE float), the channel count, the sample rate and the bits per sample. The data chunk holds the samples, little-endian. Other chunks, such as metadata, are skipped. The reader accepts 8-bit unsigned, 16-, 24- and 32-bit signed integer and 32- and 64-bit float samples, in plain or extensible headers. It returns them as f32 values scaled by for -bit integers, so full scale is . A truncated final chunk is tolerated, as many recorders leave one.
pub fn parse_wav(data: &[u8]) -> Result<WavAudio, ErrorsJSL> {
if data.get(0..4) != Some(b"RIFF") || data.get(8..12) != Some(b"WAVE") {
return Err(ERR_FORMAT);
}
let mut pos = 12;
let mut fmt: Option<(u16, u16, u32, u16)> = None; // (tag, channels, rate, bits)
let mut payload: Option<&[u8]> = None;
while pos + 8 <= data.len() {
let id = &data[pos..pos + 4];
let size = u32_at(data, pos + 4)? as usize;
let body_end = (pos + 8 + size).min(data.len()); // tolerate a truncated final chunk
let body = &data[pos + 8..body_end];
match id {
b"fmt " => {
let mut tag = u16_at(body, 0)?;
let channels = u16_at(body, 2)?;
let rate = u32_at(body, 4)?;
let bits = u16_at(body, 14)?;
if tag == 0xFFFE {
tag = u16_at(body, 24)?; // first two bytes of the sub-format GUID
}
fmt = Some((tag, channels, rate, bits));
}
b"data" => payload = Some(body),
_ => {}
}
pos += 8 + size + (size & 1);
}
let (tag, channels, sample_rate, bits) = fmt.ok_or(ERR_FORMAT)?;
let body = payload.ok_or(ERR_FORMAT)?;
if channels == 0 {
return Err(ERR_FORMAT);
}
let bytes = (bits / 8) as usize;
let samples: Vec<f32> = match (tag, bits) {
(1, 8) => body.iter().map(|&b| (b as f32 - 128.0) / 128.0).collect(),
(1, 16) => body.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b) as f32 / 32768.0).collect(),
(1, 24) => body
.as_chunks::<3>()
.0
.iter()
.map(|b| (i32::from_le_bytes([0, b[0], b[1], b[2]]) >> 8) as f32 / 8_388_608.0)
.collect(),
(1, 32) => body.as_chunks::<4>().0.iter().map(|b| (i32::from_le_bytes(*b) as f64 / 2_147_483_648.0) as f32).collect(),
(3, 32) => body.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(),
(3, 64) => body.as_chunks::<8>().0.iter().map(|b| f64::from_le_bytes(*b) as f32).collect(),
_ => return Err(ErrorsJSL::InvalidInputRange("Unsupported WAV sample format.")),
};
debug_assert!(bytes > 0);
let whole = samples.len() / channels as usize * channels as usize;
Ok(WavAudio { sample_rate, channels, samples: samples[..whole].to_vec() })
}
Writing reverses this and clips integer formats to their range. Files written by Python and read by the library:
Table 26.4. WAV files written by Python and read by the library.
| file written by Python | bytes | read by the library |
|---|---|---|
| wav 8-bit | 844 | identical |
| wav 16-bit | 1644 | identical |
| wav 24-bit | 2444 | identical |
| wav 32-bit | 3244 | largest difference 3.0e-8 |
| wav float | 3244 | identical |
| wav double | 6444 | largest difference 3.0e-8 |
And files written by the library, read by SciPy’s wavfile:
Table 26.5. WAV files written by the library and read by Python.
| file written by the library (read by) | result |
|---|---|
| WAV, 8-bit (SciPy) | uint8 at 22050 Hz; largest difference 0.0039 |
| WAV, 16-bit (SciPy) | int16 at 22050 Hz; largest difference 1.5e-05 |
| WAV, 24-bit (SciPy) | int32 at 22050 Hz; largest difference 6e-08 |
| WAV, 32-bit (SciPy) | int32 at 22050 Hz; largest difference 1.6e-10 |
| WAV, float (SciPy) | float32 at 22050 Hz; largest difference 0 |
| WAV, double (SciPy) | float64 at 22050 Hz; largest difference 0 |
The 32-bit and double-precision files differ by about because the library holds samples as f32, with a 24-bit significand.
Algorithm
Reading a WAV file.
- Check that the file begins with the tag
RIFF, a length, and the tagWAVE. - Walk the chunks that follow. Each has a four-character tag and a length; a chunk that is not recognised is skipped by its length.
- From the
fmtchunk, read the sample format (integer or floating point), the number of channels, the sampling rate and the bits per sample. If the format is the “extensible” one, the real format is given by a sub-format field later in the chunk. - From the
datachunk, read the samples, which are little-endian and interleaved (one sample for each channel in turn), and convert them tof32: integer samples are divided by their full-scale value, so that the result lies in .
Writing a WAV file: write the canonical 44-byte header (the RIFF tag and total length,
the WAVE tag, a fmt chunk of 16 bytes and the data tag and length), followed by the
interleaved little-endian samples.
Implementation
WavAudioholds the sample rate, channel count and interleavedf32samples;channel(i)extracts one channel.- Integer formats are clipped to their range on writing; floating-point formats are written as they are.
In practice
//! Writing and reading WAV files in each sample format.
use lib_jsl_file_io::{WavAudio, WavSampleFormat, encode_wav, parse_wav, read_wav_file, write_wav_file};
fn main() {
// Half a second of a 440 Hz tone in stereo, the right channel quieter.
let rate = 44_100;
let frames = rate as usize / 2;
let samples: Vec<f32> = (0..frames)
.flat_map(|i| {
let s = (2.0 * std::f32::consts::PI * 440.0 * i as f32 / rate as f32).sin();
[0.8 * s, 0.4 * s]
})
.collect();
let audio = WavAudio { sample_rate: rate, channels: 2, samples };
for format in [WavSampleFormat::Pcm8, WavSampleFormat::Pcm16, WavSampleFormat::Pcm24, WavSampleFormat::Pcm32, WavSampleFormat::Float32] {
let bytes = encode_wav(&audio, format).unwrap();
let back = parse_wav(&bytes).unwrap();
let error = audio.samples.iter().zip(&back.samples).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
println!("{format:?}: {} bytes, largest error {error:.1e}", bytes.len());
}
let path = std::env::temp_dir().join("lib_jsl_tone.wav");
write_wav_file(&path, &audio, WavSampleFormat::Pcm16).unwrap();
let read = read_wav_file(&path).unwrap();
println!("file: {} Hz, {} channels, {} frames; left channel peak {:.3}", read.sample_rate, read.channels, read.frames(), read.channel(0).iter().fold(0.0f32, |m, v| m.max(v.abs())));
}
Pcm8: 44144 bytes, largest error 3.9e-3
Pcm16: 88244 bytes, largest error 1.5e-5
Pcm24: 132344 bytes, largest error 6.0e-8
Pcm32: 176444 bytes, largest error 2.3e-10
Float32: 176444 bytes, largest error 0.0e0
file: 44100 Hz, 2 channels, 22050 frames; left channel peak 0.800
Each extra 8 bits per sample cuts the round-trip error by , down to the precision of the f32 samples themselves.
Strengths
- WAV reading and writing for every common PCM and float layout, checked against Python’s
waveand SciPy. - Tolerant reading: unknown chunks are skipped and a truncated final chunk is accepted.
Weaknesses
- No compressed formats (MP3, AAC, FLAC), and no reading of metadata chunks.
- WAV samples are held as
f32, so 32-bit integer and 64-bit float data lose precision beyond 24 bits.
Exercises
- Compute the bit rate of 16-bit stereo audio at 44.1 kHz, and the size of an hour of it.
- Explain why 8-bit WAV samples are unsigned while all wider integer samples are signed, and how the reader centres them.
- Explain why a -bit quantiser gives about dB SNR on a full-scale sine wave.
- Why does the reader scale -bit integers by rather than , and what happens to full-scale positive samples?
- Write the 44-byte canonical WAV header for 2 seconds of mono 16-bit audio at 8 kHz, field by field.
Hints and answers
- bit/s, i.e. bytes/s; an hour is bytes MB.
- In the WAV format, 8-bit samples are unsigned (offset 128) for historical reasons; wider samples are two’s complement signed. The reader subtracts 128 to centre them.
- A full-scale sine has power with , while uniform quantisation noise has power with : SNR dB.
- Dividing by maps to exactly and the largest positive value to just below ; dividing by would map below .
- The 44-byte header:
RIFF, size ,WAVE,fmt, 16, format 1, 1 channel, rate 8000, byte rate 16000, block align 2, 16 bits,data, data size 32000.
Further reading
- IBM and Microsoft, Multimedia Programming Interface and Data Specifications 1.0, 1991 (the RIFF and WAVE specification).
- Microsoft, “WAVEFORMATEXTENSIBLE structure”, Windows multimedia documentation.
- K. C. Pohlmann, Principles of Digital Audio, 6th ed., McGraw-Hill, 2011.