liveBook · Manning

Sampling rate

As explained in Learn Haskell by Example

Sample rate is the number of audio samples represented or processed per second.

Sampling rate is the number of numeric audio samples captured or generated each second. A sampled signal approximates a continuous analog signal, so its rate limits how accurately it can reproduce changes over time. For a signal with a known highest frequency, the rate must be at least twice that frequency; 44.1 kHz is a common choice because frequencies above 22 kHz are not relevant to human hearing. section 10.1

In a mono synthesizer, a sample can be a Double and a signal a list of samples. Set a single sampleRate value, then derive integer counts from it: samples per period are sampleRate / frequency, and samples for a duration are duration * sampleRate. Round these results because a signal cannot contain a fractional sample. section 10.1.1

Listing 10.1 Types and helper functions for dealing with signals
type Sample = Double       #1

type Signal = [Sample]    #1  

type Hz = Double          #1

type Seconds = Double     #1

sampleRate :: Double     #2
sampleRate = 44100

samplesPerPeriod :: Hz -> Int
samplesPerPeriod hz = round $ sampleRate / hz            #3

samplesPerSecond :: Seconds -> Int
samplesPerSecond duration = round $
 duration * sampleRate       #4

This helper module fixes the rate at 44,100 samples per second and turns frequencies and durations into the integer sample counts needed to generate a signal. section 10.1.1

Exporting generated audio

A tone generator uses samplesPerPeriod and samplesPerSecond to create waveform values. When writing a WAV file, place the same rate in the Audio record, alongside one channel and converted sample data. Keeping generation and file metadata aligned lets the exported data be interpreted at the intended speed. section 10.1.2 section 10.1.2

How Learn Haskell by Example covers it

How deep it goes
Defines sampling rate, relates it to frequency limits, and implements rate-based sample-count helpers without array internals.
Examples
Uses 44.1 kHz audio, period and duration calculations, generated tones, and a WAV file containing four waveforms.
What it assumes
Teaches rate-based calculations from basic numeric values while introducing required Haskell numeric type classes.
What you can do after
Build it from scratch by deriving integer signal lengths and writing matching WAV sample-rate metadata.
How it connects
Connects sampling to signal resolution, Nyquist–Shannon sampling theorem, frequency, duration, waveforms, and WAV files.

Also explained in

Compare how 2 books explain sampling rate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.