Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """Interpret sun audio headers.""" |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 3 | MAGIC = '.snd' |
| 4 | |
Fred Drake | 9b8d801 | 2000-08-17 04:45:13 +0000 | [diff] [blame] | 5 | class error(Exception): |
| 6 | pass |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 7 | |
| 8 | |
Guido van Rossum | d482e8a | 1992-06-03 16:47:49 +0000 | [diff] [blame] | 9 | def get_long_be(s): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 10 | """Convert a 4-char value to integer.""" |
Guido van Rossum | d482e8a | 1992-06-03 16:47:49 +0000 | [diff] [blame] | 11 | return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 12 | |
| 13 | |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 14 | def gethdr(fp): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 15 | """Read a sound header from an open file.""" |
Fred Drake | 8152d32 | 2000-12-12 23:20:45 +0000 | [diff] [blame] | 16 | if fp.read(4) != MAGIC: |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 17 | raise error, 'gethdr: bad magic word' |
Guido van Rossum | d482e8a | 1992-06-03 16:47:49 +0000 | [diff] [blame] | 18 | hdr_size = get_long_be(fp.read(4)) |
| 19 | data_size = get_long_be(fp.read(4)) |
| 20 | encoding = get_long_be(fp.read(4)) |
| 21 | sample_rate = get_long_be(fp.read(4)) |
| 22 | channels = get_long_be(fp.read(4)) |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 23 | excess = hdr_size - 24 |
| 24 | if excess < 0: |
| 25 | raise error, 'gethdr: bad hdr_size' |
| 26 | if excess > 0: |
| 27 | info = fp.read(excess) |
| 28 | else: |
| 29 | info = '' |
| 30 | return (data_size, encoding, sample_rate, channels, info) |
| 31 | |
| 32 | |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 33 | def printhdr(file): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 34 | """Read and print the sound header of a named file.""" |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 35 | hdr = gethdr(open(file, 'r')) |
| 36 | data_size, encoding, sample_rate, channels, info = hdr |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 37 | while info[-1:] == '\0': |
Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 38 | info = info[:-1] |
| 39 | print 'File name: ', file |
| 40 | print 'Data size: ', data_size |
| 41 | print 'Encoding: ', encoding |
| 42 | print 'Sample rate:', sample_rate |
| 43 | print 'Channels: ', channels |
| 44 | print 'Info: ', `info` |