[Tutor] Musical note on python

eryksun eryksun at gmail.com
Fri Sep 14 13:54:42 CEST 2012


On Thu, Sep 13, 2012 at 8:37 PM, D.V.N.Sarma డి.వి.ఎన్.శర్మ
<dvnsarma at gmail.com> wrote:
>
> Error: "name data undefined"
>
>>     import wave
>>     import winsound
>>     from cStringIO import StringIO
>>
>>     def get_wave(data):
>>         f = StringIO()
>>         w = wave.open(f, 'w')
>>         w.setnchannels(1) # mono
>>         w.setsampwidth(2) # 2 bytes
>>         w.setframerate(48000) # samples/second
>>         w.writeframes(data)
>>         return f.getvalue()
>>
>>
>> Then play the sound like this (_untested_):
>>
>>
>>     wave_data = get_wave(data)
>>     windsound.PlaySound(wave_data, winsound.SND_MEMORY)


"data" is a byte string of packed samples. For example, the function
packwave() converts a sequence of floats into a byte string. It
assumes the input is in the range [-1.0, 1.0]. It scales this range to
[-32767, 32767]. Each scaled value is packed as 2 bytes in little
endian order. That means the order is (low byte, high byte).

For example, 32767 becomes "\xff\x7f", where 0xff (255) is the low
byte and 0x7f (127) is the high byte. You can calculate the value as
follows: 255 + 127*256 = 32767. Since the format is 2's complement,
the next value up, "\x00\x80", wraps around to -32768. Then "\x01\x80"
is -32767, and so on, up to -1 at "\xff\xff".

http://docs.python.org/library/struct

http://en.wikipedia.org/wiki/Endianness

http://en.wikipedia.org/wiki/Two%27s_complement


More information about the Tutor mailing list