如何跨平台从 Haskell 代码播放音频文件

How to play an audio file from Haskell code, cross-platform

我正在编写一个在 Linux、Windows 和 OS X 上运行的 Haskell 命令行应用程序。我现在必须播放音频文件 (.wav.ogg.mp3)。我将如何实现一个功能

playAudioFile :: FilePath -> IO ()

甚至更好

playAudio :: ByteString -> IO ()

那只适用于所有系统?

(我很乐意调用常用的命令行工具,也不介意将它们捆绑到 Windows 发行版中。)

这是我使用 SDL-1.2 编写的代码:

module PlaySound (withSound, playSound) where

import Control.Monad
import System.IO
import System.Directory
import Data.Foldable
import Control.Exception
import qualified Data.ByteString.Lazy as B
import Foreign.ForeignPtr

import Graphics.UI.SDL as SDL
import Graphics.UI.SDL.Mixer as Mix

withSound :: IO a -> IO a
withSound = bracket_ init cleanup
  where
    init = do
        SDL.init [SDL.InitAudio]
        getError >>= traverse_ putStrLn
        ok <- Mix.tryOpenAudio Mix.defaultFrequency Mix.AudioS16LSB 2  4096
        unless ok $
            putStrLn "Failed to open SDL audio device"

    cleanup = do
        Mix.closeAudio
        SDL.quit

playSound :: B.ByteString -> IO ()
playSound content = do
        dir <- getTemporaryDirectory
        (tmp, h) <- openTempFile dir "sdl-input"
        B.hPutStr h content
        hClose h

        mus <- Mix.loadMUS tmp
        Mix.playMusic mus 1
        wait

        -- This would double-free the Music, as it is also freed via a
        -- finalizer
        --Mix.freeMusic mus
        finalizeForeignPtr mus
        removeFile tmp

wait :: IO ()
wait = do
    SDL.delay 50
    stillPlaying <- Mix.playingMusic
    when stillPlaying wait

程序最终运行正常,但是

  • 在 Windows 下编译 SDL 绑定很棘手。我关注了this nice explanation on how to do it
  • SDL-1.2 的 SDL 绑定似乎没有维护并且 do not even compile with GHC-7.8 or newer。一开始我没有注意到,因为我的发行版 (Debian) 围绕这些问题打了补丁,但这意味着我的用户不能再轻易 cabal install 依赖项了。
  • 有针对 SDL-2 的绑定,但是 none 针对 SDL_mixer,这是我需要的(我相信)。

所以我会很乐意阅读更好的答案。