sunaudio.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """Interpret sun audio headers."""
  2. MAGIC = '.snd'
  3. class error(Exception):
  4. pass
  5. def get_long_be(s):
  6. """Convert a 4-char value to integer."""
  7. return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
  8. def gethdr(fp):
  9. """Read a sound header from an open file."""
  10. if fp.read(4) != MAGIC:
  11. raise error, 'gethdr: bad magic word'
  12. hdr_size = get_long_be(fp.read(4))
  13. data_size = get_long_be(fp.read(4))
  14. encoding = get_long_be(fp.read(4))
  15. sample_rate = get_long_be(fp.read(4))
  16. channels = get_long_be(fp.read(4))
  17. excess = hdr_size - 24
  18. if excess < 0:
  19. raise error, 'gethdr: bad hdr_size'
  20. if excess > 0:
  21. info = fp.read(excess)
  22. else:
  23. info = ''
  24. return (data_size, encoding, sample_rate, channels, info)
  25. def printhdr(file):
  26. """Read and print the sound header of a named file."""
  27. hdr = gethdr(open(file, 'r'))
  28. data_size, encoding, sample_rate, channels, info = hdr
  29. while info[-1:] == '\0':
  30. info = info[:-1]
  31. print 'File name: ', file
  32. print 'Data size: ', data_size
  33. print 'Encoding: ', encoding
  34. print 'Sample rate:', sample_rate
  35. print 'Channels: ', channels
  36. print 'Info: ', repr(info)