Skip to content

Instantly share code, notes, and snippets.

@relrod
Last active August 26, 2015 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save relrod/726a0e1a5c55f2a95d16 to your computer and use it in GitHub Desktop.
Save relrod/726a0e1a5c55f2a95d16 to your computer and use it in GitHub Desktop.
Playing around with audio
module Main where
import Data.Binary.Put
import qualified Data.ByteString.Lazy as BL
import Data.Word
newtype Seconds = Seconds Double
newtype Hertz = Hertz Double
sampleRate :: Double
sampleRate = 16000
{-# INLINE sampleRate #-}
nextPhase :: Double -> Hertz -> Double
nextPhase phase (Hertz f) = phase + ((2 * pi * f) / sampleRate)
{-# INLINE nextPhase #-}
produceSeconds :: Seconds -> Hertz -> [Double]
produceSeconds (Seconds s) h =
take (floor (sampleRate * s)) . map sin $
iterate (flip nextPhase h) 0
{-# INLINE produceSeconds #-}
volumeize :: Word16 -> [Double] -> [Double]
volumeize m l = map (fromIntegral m *) l
{-# INLINE volumeize #-}
toWord16 :: [Double] -> [Word16]
toWord16 = map round
{-# INLINE toWord16 #-}
putSamples :: [Word16] -> Put
putSamples l = mapM_ putWord16le l
{-# INLINE putSamples #-}
main :: IO ()
main = do
let r = toWord16 . volumeize (maxBound `div` 2) $ produceSeconds (Seconds 1) (Hertz 1000)
BL.writeFile "/tmp/out.raw" (runPut . putSamples $ r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment