这就是我所拥有的。受此问题的启发,它会生成一个440 Hz 正弦波的 5 秒Au 文件。
-- file: tone.hs
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Binary.Put
-- au format header: https://en.wikipedia.org/wiki/Au_file_format
header :: Double -> Integer -> Integer -> Put
header dur rate bps = do
putLazyByteString $ BLC.pack ".snd"
putWord32be 24
putWord32be $ fromIntegral $ floor $ fromIntegral bps * dur * fromIntegral rate
putWord32be 3
putWord32be $ fromIntegral rate
putWord32be 1
-- audio sample data
samples :: Double -> Integer -> Integer -> Double -> Double -> Put
samples dur rate bps freq vol =
foldl1 (>>) [put i | i <- [0..numSamples-1]]
where
numSamples = floor $ fromIntegral rate * dur
scale i = 2 * pi * freq / fromIntegral rate * fromIntegral i
sample i = vol * sin (scale i)
coded samp = floor $ (2 ^ (8*bps-1) - 1) * samp
put i = putWord16be $ coded $ sample i
freq = 440 :: Double -- 440 Hz sine wave
dur = 5 :: Double -- played for 5 seconds
rate = 44100 :: Integer -- at a 44.1 kHz sample rate
vol = 0.8 :: Double -- with a peak amplitude of 0.8
bps = 2 :: Integer -- at 16 bits (2 bytes) per sample
main =
BL.putStr $ runPut au
where
au = do
header dur rate bps
samples dur rate bps freq vol
如果您正在运行 Linux,则可以使用runghc tone.hs | aplay
. 对于其他操作系统,您可能可以将输出重定向到.au
文件并在音频播放器中播放。
我怎样才能使这段代码更地道?例如:
- 我
fromIntegral
到处写。我可以避免吗? - 我应该/可以使用不同的包来输出二进制数据吗?
- 我在使用合理的类型吗?