Martin McBride, 2021-08-23
Tags python open source github pysound
Pysound simple example
Here is a very simple Pysound program to create a sound file.
Before running this, you will need to install Pysound, and also make sure you have NumPy installed.
In this example we will create a short WAV file that plays a constant sine wave tone.
Here is the code:
from pysound import buffer from pysound import soundfile from pysound import oscillators params = buffer.BufferParams() data = oscillators.sine_wave(params) soundfile.save(params, '/tmp/test.wav', data)
After importing several modules, there are just 3 lines of code.
First we create a
BufferParams object. This object controls the length of the sound, and also the sample rate. The default constructor specifies a sound that is 1 second long, and has a sampe rate of 44,100 samples per second (this is the sample rate used by an audio CD):
params = buffer.BufferParams()
Next, we call the
sine_wave function, that creates a sine wave tone.
data = oscillators.sine_wave(params)
We pass in the
params object to tell the function how long the sound should last, and what sample rate to use.
sine_wave function takes several other parameters too, but we will use the default values. This creates a sine wave tone with an audio frequency of 400 Hz and an amplitude of 1.0.
The function returns a NumPy array, that we store in
data. This is just a standard NumPy array.
Finally, we store the data in a WAV file:
soundfile.save(params, '/tmp/test.wav', data)
This takes the data and converts it to WAV format. It is stored as test.wav in the
/tmp folder. You might want to change that to C:/temp if you are using a Windows system.
Join me on substack to keep up to date with this blog