load_wav.monkey2 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "<libc>"
  2. Namespace std.audio
  3. Private
  4. Using std.stream
  5. Struct WAV_Header
  6. '
  7. Field RIFF:Int
  8. Field len:Int
  9. Field WAVE:Int
  10. Field fmt:Int
  11. Field headerLen:Int
  12. '
  13. Field formatTag:Short
  14. Field numChannels:Short
  15. Field samplesPerSec:Int
  16. Field avgBytesPerSec:Int
  17. Field blockalignment:Short
  18. Field bitsPerSample:Short
  19. '
  20. End
  21. Function ReadWAV:AudioData( stream:std.stream.Stream )
  22. Local header:=New WAV_Header
  23. Local header_sz:=libc.sizeof( header )
  24. If stream.Read( Varptr header,header_sz )<>header_sz Return null
  25. If header.RIFF<>$46464952 Return Null
  26. Local format:AudioFormat
  27. If header.numChannels=1 And header.bitsPerSample=8
  28. format=AudioFormat.Mono8
  29. Else If header.numChannels=1 And header.bitsPerSample=16
  30. format=AudioFormat.Mono16
  31. Else If header.numChannels=2 And header.bitsPerSample=8
  32. format=AudioFormat.Stereo8
  33. Else If header.numChannels=2 And header.bitsPerSample=16
  34. format=AudioFormat.Stereo16
  35. Else
  36. Return Null
  37. Endif
  38. Local skip:=header.headerLen-16
  39. If skip>0 stream.Skip( skip )
  40. While Not stream.Eof
  41. Local tag:=stream.ReadInt()
  42. Local size:=stream.ReadInt()
  43. If tag<>$61746164 '"DATA"
  44. stream.Skip( size )
  45. Continue
  46. Endif
  47. Local data:=New AudioData( size/BytesPerSample( format ),format,header.samplesPerSec )
  48. stream.Read( data.Data,size )
  49. Return data
  50. Wend
  51. Return Null
  52. End
  53. Public
  54. Function LoadAudioData_WAV:AudioData( path:String )
  55. Local stream:=std.stream.Stream.Open( path,"r" )
  56. If Not stream Return Null
  57. Local data:=ReadWAV( stream )
  58. stream.Close()
  59. Return data
  60. End