[Tutor] Processing a string of bytes

David Perlman dperlman at wisc.edu
Thu Sep 3 21:17:11 CEST 2009


I have successfully used the builtin "wave" module to read an audio  
file in as a string of bytes:

 >>> x=wave.open('DaCWL.wav','rb')
 >>> x.getparams()
(1, 2, 44100, 15440, 'NONE', 'not compressed')
 >>> samp=x.readframes(15440)
 >>> type(samp)
<type 'str'>

The x.getparams() indicates that there is one audio channel, 2 bytes  
per sample, 44100 sampling rate, and 15440 samples in the file.

What I would like to know is, what is the most elegant and (dare I say  
it) pythonic way to do some processing on the resulting string of  
bytes, which represents a sequence of two-byte signed integers?  The  
goal is to normalize the file, by taking the root-mean-square and then  
scaling every sample accordingly.  So I only need to do simple  
arithmetic on the sample values.

The obvious thing to do is to use a loop to get two bytes at a time,  
convert them to int, and work on the resulting list of ints.  However  
this seems kind of inelegant, and wasteful of space, since python ints  
are way more than two bytes.  Also I'm not sure if there's a  
convenient built-in way to do that conversion.

So, in summary, I would be interested in either of two things:
1. advice on how to do arithmetic on the string of bytes without  
converting it to a list of ints first, or
2. advice on how to convert it to a list of ints, and then back to a  
string of bytes.

Thanks very much!

--
-dave----------------------------------------------------------------
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard





More information about the Tutor mailing list