Chapter 20

Sound Synthesis

Now that we know how samples are used to represent sounds in a WAV file, we can write programs to create our own sounds. In other words, we can create synthesizers.

This program listing is not complete: you will need to add appropriate imports, the writewav() function from Listing 19.1, and clampsample() from Exercise 19.13.

Listing 20.1: Synthesizer

 1 # synth.py
 2
 3 # imports and some function definitions deleted
 4
 5 def sinenote(step, sec, sampfreq):
 6 data = array.array("h")
 7 samples = int(sampfreq * sec)
 8 freq = 440 * 2 ** (step / 12)
 9 for i in range(samples):
10  y = 32767 * sin(2.0 * pi * freq * i / sampfreq)
11  data.append(clampsample(y, "h"))
12  return data
13
14 def notes(notefn, steps, sec, sampfreq): ...

Get A Concise Introduction to Programming in Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.