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


