用Haskell播放一个wav文件

时间:2012-12-22 18:52:44

标签: haskell audio wav

是否有一种简单,直接的方法可以使用某些库从Haskell播放WAV文件,并且可能会让我一次播放很多声音?

我知道OpenAL但是我没有写一些高级音频合成程序,我只是想播放一些声音来播放一些东西。理想情况下,API可能类似于:

readWavFile :: FilePath -> IO Wave
playWave :: Wave -> IO ()
playWaveNonBlocking :: Wave -> IO ()

这个接近于仅启动mplayer或其他东西。或者试图将wav直接捕获到/ dev / snd /或某些。

3 个答案:

答案 0 :(得分:33)

这是如何使用SDL一次在多个声道上播放多个声音。我认为这回答了问题标准。 WAV文件,简单,Haskell,多个频道。

import Control.Monad
import Control.Monad.Fix
import Graphics.UI.SDL as SDL
import Graphics.UI.SDL.Mixer as Mix

main = do
  SDL.init [SDL.InitAudio]
  result <- openAudio audioRate audioFormat audioChannels audioBuffers
  classicJungle <- Mix.loadWAV "/home/chris/Samples/ClassicJungle/A4.wav"
  realTech      <- Mix.loadWAV "/home/chris/Samples/RealTech/A4.wav"
  ch1 <- Mix.playChannel anyChannel classicJungle 0
  SDL.delay 1000
  ch2 <- Mix.playChannel anyChannel realTech 0
  fix $ \loop -> do
    SDL.delay 50
    stillPlaying <- numChannelsPlaying
    when (stillPlaying /= 0) loop
  Mix.closeAudio
  SDL.quit

  where audioRate     = 22050
        audioFormat   = Mix.AudioS16LSB
        audioChannels = 2
        audioBuffers  = 4096
        anyChannel    = (-1)

答案 1 :(得分:10)

我意识到这实际上并不是一种方便的方法,但我有测试代码,所以......

{-# LANGUAGE NoImplicitPrelude #-}
module Wav (main) where

import Fay.W3C.Events
import Fay.W3C.Html5

import Language.Fay.FFI
import Language.Fay.Prelude

main :: Fay ()
main = addWindowEventListener "load" run

run :: Event -> Fay Bool
run _ = do
    aud <- mkAudio
    setSrc aud "test.wav"
    play aud
    return False


mkAudio :: Fay HTMLAudioElement
mkAudio = ffi "new Audio()"

addWindowEventListener :: String -> (Event -> Fay Bool) -> Fay ()
addWindowEventListener = ffi "window['addEventListener'](%1,%2,false)"

你去了 - 由于HTML5的强大功能,在Haskell中播放WAV文件!您所要做的就是启动Web浏览器而不是mplayer。 :D

答案 2 :(得分:4)

通过ALUT使用OpenAL:

import Control.Monad
import Sound.ALUT

playSound :: IO ()
playSound =
  withProgNameAndArgs runALUTUsingCurrentContext $ \_ _ ->
  do
    (Just device) <- openDevice Nothing
    (Just context) <- createContext device []
    currentContext $= Just context
    buffer1 <- createBuffer $ Sine 440 0 1
    buffer2 <- createBuffer HelloWorld
    [source] <- genObjectNames 1
    queueBuffers source [buffer1,buffer2]
    play [source]
    sleep 4
    closeDevice device
    return ()

main = playSound

加载wav文件:

buffer3 <- createBuffer $ File "/path/to/file.wav"

归功于Chris Double:http://bluishcoder.co.nz/articles/haskell/openal.html