``````

In :

import math
import pyaudio

``````

This makes a sound!

``````

In :

PyAudio = pyaudio.PyAudio

BITRATE = 24000 #number of frames per second/frameset.
FREQUENCY = 261.6 #Hz, waves per second, 261.63=C4-note.
LENGTH = 1. #seconds to play sound

NUMBEROFFRAMES = int(BITRATE * LENGTH)
RESTFRAMES = NUMBEROFFRAMES % BITRATE
WAVEDATA = ''

for x in xrange(NUMBEROFFRAMES):
WAVEDATA = WAVEDATA+chr(int(math.sin(x/((BITRATE/FREQUENCY)/math.pi))*127+128))

#fill remainder of frameset with silence
for x in xrange(RESTFRAMES):
WAVEDATA = WAVEDATA+chr(128)

p = PyAudio()
stream = p.open(format = p.get_format_from_width(1),
channels = 1,
rate = BITRATE,
output = True)
stream.write(WAVEDATA)
stream.stop_stream()
stream.close()
p.terminate()

``````

## Write a file

``````

In :

import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

``````
``````

In :

from struct import pack
from math import sin, pi

``````
``````

In :

# create a sound file in AU format playing a sine wave
# of a given frequency, duration and volume
def au_file(name='test.au', freq=440, dur=1000, vol=0.5, lead=0, tail=0):
"""
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')

total = lead + dur + tail

values = []

# header needs size, encoding=2, sampling_rate=8000, channel=1
fout.write(pack('>4s5L', '.snd'.encode("utf8"), 24, 8*total, 2, 8000, 1))
factor = 2 * pi * freq/8000

for seg in range(8 * lead):
val = pack('b', 0)
fout.write(val)
values.append(0)

# write data
for seg in range(8 * dur):
# sine wave calculations
sin_seg = sin(seg * factor)
v = vol * 127 * sin_seg
val = pack('b', int(v))
fout.write(val)
values.append(v)

# write tail
for seg in range(8 * tail):
val = pack('b', 0)
fout.write(val)
values.append(0)

fout.close()
print("File %s written" % name)

return values

``````
``````

In :

sound = au_file(name='sound440_2.au', freq=150, dur=500, vol=1.0, lead=500, tail=500)

``````
``````

File sound440_2.au written

``````
``````

In :

plt.figure(figsize=(20,4))
plt.plot(sound)
plt.show()

``````
``````

``````
``````

In [ ]:

``````