Synthesizing music
Now that we know how to generate audio, let's use this principle to synthesize some music. You can check out this link, http://www.phy.mtu.edu/~suits/notefreqs.html. This link lists various notes, such as A, G, D, and so on, along with their corresponding frequencies. We will use this to generate some simple music.
How to do it…
Create a new Python file, and import the following packages:
import json import numpy as np from scipy.io.wavfile import write import matplotlib.pyplot as plt
Define a function to synthesize a tone, based on input parameters:
# Synthesize tone def synthesizer(freq, duration, amp=1.0, sampling_freq=44100):
Build the time axis values:
# Build the time axis t = np.linspace(0, duration, duration * sampling_freq)
Construct the audio sample using the input arguments, such as amplitude and frequency:
# Construct the audio signal audio = amp * np.sin(2 * np.pi * freq * t) return audio.astype(np.int16)
Let's define the
main
function. You have...