Creating and playing a sine wave sound (Python)

vegaseat 1 Tallied Votes 2K Views Share

This code creates a sound file in Sun's simple AU audio format of a sine wave of given frequency, duration and volume.

# create a soundfile in AU format playing a sine wave
# of a given frequency, duration and volume
# tested with Python25   by vegaseat     29jan2008

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='sound800.au', freq=800, dur=2000, vol=0.8)
    
    # if you have Windows, you can test the audio file
    # otherwise comment this code out
    import os
    os.startfile('sound800.au')
morrna 0 Newbie Poster

I'm having a problem running this code with Python 3.1. It complains that the argument of fout.write() must be bytes or buffer, not str. Anyone know how to fix this?

ZZucker 342 Practically a Master Poster

Here is the modification of vegaseat's code that will work with both Python27 and Python32:

# create a sound file in AU format playing a sine wave
# of a given frequency, duration and volume
# vegaseat code modified to work with Python27 and Python32

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 sine wave audio file
    of frequency freq (Hz)
    of duration dur (milliseconds)
    and volume vol (max is 1.0)
    """
    fout = open(name, 'wb')
    # header needs size, encoding=2, sampling_rate=8000, channel=1
    fout.write(pack('>4s5L', '.snd'.encode("utf8"), 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)
        val = pack('b', int(vol * 127 * sin_seg))
        fout.write(val)
    fout.close()
    print("File %s written" % name)


# 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')
Hubert_2 0 Newbie Poster

Tried to run the program but had an error on line 4

bellow the error

C:\Users\user pc\AppData\Local\Programs\Python\Python35-32\python "C:\Users\user pc\SkyDrive\ISN\son internet test.py"
Process started >>>
File "C:\Users\user pc\SkyDrive\ISN\son internet test.py", line 4
from struct import pack
^
IndentationError: unexpected indent
Process finished. (Exit code 1)

I'm sure it has nothing to do with the code pasted @Zzucker. Just check your use of tabs and spaces and make sure you've aligned everything right. Python is so particular about indentation (It's part of the syntax).

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.