File: AudioExample.hs

package info (click to toggle)
haskell-sdl2 2.5.5.0-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 17,348 kB
  • sloc: haskell: 10,160; ansic: 102; makefile: 5
file content (50 lines) | stat: -rw-r--r-- 1,603 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
{-# LANGUAGE GADTs #-}

module AudioExample where

import Data.IORef
import Control.Monad
import Control.Concurrent
import Data.Int (Int16, Int32)
import SDL
import qualified Data.Vector.Storable.Mutable as V

sinSamples :: [Int16]
sinSamples =
  map (\n ->
         let t = fromIntegral n / 48000 :: Double
             freq = 440
         in round (fromIntegral (maxBound `div` 2 :: Int16) * sin (2 * pi * freq * t)))
      [0 :: Int32 ..]

audioCB :: IORef [Int16] -> AudioFormat sampleType -> V.IOVector sampleType -> IO ()
audioCB samples format buffer =
  case format of
    Signed16BitLEAudio ->
      do samples' <- readIORef samples
         let n = V.length buffer
         zipWithM_ (V.write buffer)
                   [0 ..]
                   (take n samples')
         writeIORef samples
                    (drop n samples')
    _ -> error "Unsupported audio format"

main :: IO ()
main =
  do initializeAll
     samples <- newIORef sinSamples
     (device,_) <-
       openAudioDevice
         OpenDeviceSpec {SDL.openDeviceFreq =
                           Mandate 48000
                        ,SDL.openDeviceFormat =
                           Mandate Signed16BitNativeAudio
                        ,SDL.openDeviceChannels =
                           Mandate Mono
                        ,SDL.openDeviceSamples = 4096 * 2
                        ,SDL.openDeviceCallback = audioCB samples
                        ,SDL.openDeviceUsage = ForPlayback
                        ,SDL.openDeviceName = Nothing}
     setAudioDevicePlaybackState device Play
     forever (threadDelay maxBound)