liveBook · Manning

Audio

As explained in Learn Haskell by Example

Audio is an HCodecs record type containing audio sample data, sample-rate information, and channel information.

Audio is an HCodecs record that packages a sample rate, channel count, and SampleData for writing uncompressed WAV files. section 10.1.2

Construct an Audio value by:

  • Converting a Signal into SampleData with listArray and fromSample. section 10.1.2
  • Clamping signal values before conversion so samples remain within the required range. section 10.1.2
  • Setting the sample rate and channel number, then passing the record to Codec.Wav.exportFile. section 10.1.2
Listing 10.6 Functions to write audio data to WAV files
import Util.Types
import qualified Codec.Wav     #1
import Data.Audio              #1

writeWav :: FilePath -> Signal -> IO ()
writeWav filePath signal = do
  putStrLn $
    "Writing " ++ show (length signal) ++ " samples to " ++ filePath
  let sampleData = signalToSampleData $ limit signal    #2
      audio =
        Audio                                               #3
          { Data.Audio.sampleRate = round Util.Types.sampleRate,
            channelNumber = 1,
            sampleData = sampleData
          }
  Codec.Wav.exportFile filePath audio    #4

Inspect the complete writeWav implementation, including limiting, Audio construction, and WAV export. section 10.1.2

Exporting generated tones

Combining four generated waveforms with tone and concatMap produces a signal that writeWav can save as 4waves.wav. section 10.1.2

How Learn Haskell by Example covers it

How deep it goes
Explains record construction and signal conversion, while deferring the internal implementation of arrays.
Examples
Uses generated sine, triangle, sawtooth, and square waves combined into a four-wave WAV file.
What it assumes
Assumes Signal and Sample types, while teaching the required SampleData conversion and array bounds.
What you can do after
Builds an Audio value and exports bounded signal data to a WAV file with Codec.Wav.exportFile.
How it connects
Connects Signal, SampleData, arrays, sample conversion, waveform generation, and WAV export.

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.