liveBook · Manning

Clipping

As explained in Learn Haskell by Example

Audio clipping is distortion caused when a signal exceeds the allowed or representable amplitude range and is truncated.

Audio clipping is distortion produced when sample levels exceed the allowed range from -1 to 1 and are cut off by a limiting function. section 11.2.1

The risk appears when overlapping signals are added during polyphonic synthesis. Mixing must preserve every sample within the permitted range rather than summing signals unchanged. section 11.2.1

Prevent clipping while mixing signals by following this pattern:

  • Add signals one after another with a fold, extending through the longest signal instead of stopping at the shortest. section 11.2.1
  • Divide the accumulated samples by the number of signals so their combined levels stay within the permitted maximum and minimum. section 11.2.1
  • Group overlapping events, render each group, and mix the resulting signals with the clipping-safe mixer. section 11.2.2

Polyphonic composition

Three melodies can begin together, producing simultaneous tones. Their signals are mixed and divided by the number of signals, preventing the combined waveform from being truncated. section 11.2.2

Listing 11.6 Function to mix multiple signals into a single signal
module Sound.Sound where

...
import Data.List (foldl')
...

mix :: [Signal] -> Signal
mix signals = (/ n) <$> foldl' addSignals [] signals  #1
  where
    n :: Double
    n = fromIntegral $ length signals  #2

    addSignals :: Signal -> Signal -> Signal
    addSignals xs [] = xs  #3
    addSignals [] ys = ys  #3
    addSignals (x : xs) (y : ys) = (x + y) :
 addSignals xs ys  #4

Inspect the Haskell mixer that folds signals together, handles unequal lengths, and scales the result by the signal count. section 11.2.1

How Learn Haskell by Example covers it

How deep it goes
Defines clipping, explains its cause, and implements prevention through folded signal addition and amplitude scaling.
Examples
Uses overlapping melodies and a Haskell mix function to demonstrate safe combination of generated signals.
What it assumes
Assumes signals, performances, events, and folds while explaining overlapping-event grouping in the synthesis pipeline.
What you can do after
Build it from scratch by folding audio signals together and scaling their samples to avoid clipping.
How it connects
Connects clipping with signal mixing, polyphony, overlapping events, folds, and amplitude limits.

Also explained in

Compare how 3 books explain clipping →

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.