HiHe 174 Junior Poster

The small code shown below works fine with Python26, however Python31 gives an error:
fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
TypeError: Can't convert 'bytes' object to str implicitly

Does anyone know what I need to do to make it work with Python31?

# create a soundfile in AU format playing a sine wave
# of a given frequency, duration and volume
# using Python26

from struct import pack
from math import sin, pi

def au_file(name='test.au', freq=440, dur=1000, vol=0.5):
    """
    creates an AU format audio file of a sine wave
    of frequency freq (Hz)
    for duration dur (milliseconds)
    at volume vol (max is 1.0)
    """
    fout = open(name, 'wb')
    # header needs size, encoding=2, sampling_rate=8000, channel=1
    fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
    factor = 2 * pi * freq/8000
    # write data
    for seg in range(8 * dur):
        # sine wave calculations
        sin_seg = sin(seg * factor)
        fout.write(pack('b', vol * 127 * sin_seg))
    fout.close()

# test the module ...
if __name__ == '__main__':
    au_file(name='sound440.au', freq=440, dur=2000, vol=0.8)

    # if you have Windows, you can test the audio file
    # otherwise comment this code out
    import os
    os.startfile('sound440.au')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.