O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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): ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required