# Making Sinusoids with Python

I’ve been spending a fair amount of time lately learning Python, but most of my efforts have been focused on the turtle graphics module. It’s a lot of fun, and some of the images I’ve been able to come up with are quite interesting (to me, at least), but what I really want to do is learn how to do things with audio. So I’ve started studying DSP. I’m pretty confortable with continuous functions, but discrete functions can be a bit of a challenge at first - indexes, the meaning of frequency and time, etc. With a little practice - which is all this post is - it becomes clear pretty quickly. Along the way, I get some practice plotting with Matplotlib, Numpy and Scipy. First order of business, I want to understand sinusoid generation. The basic equation is:

\[x(t) = Acos(2{\pi}ft + {\phi}) \]

Here is a plot of a 5 Hz sinusoid with a phase delay of pi/4 radians

The above is “sampled” in a sense, in that it is based on an array of length 100 with each element spaced by .01.

To base it on samples explicitly you can use one of two expressions:

\(x = Acos(2{\pi}fnT + {\phi})\), where n is the sample index and T is the sample period, or

\(x = Acos(2{\pi}fn/N + {\phi})\), where n is the sample index and N is the number of samples.

\(x = Acos(2{\pi}fnT + {\phi})\) gives:

\(x = Acos(2{\pi}fn/N + {\phi})\) is “independent” of time, in that frequency depends on the sample rate, or really on the time basis of the sample rate. So if your sample rate is 100 samples per day and f = 5, your frequency would 5 cycles per day.

Complex sinusoids have the form:

\(e^{j(2{\pi}ft +{\phi})} = cos(2{\pi}ft) + jsin(2{\pi}ft)\) for continuous time and \(x = e^{j(2{\pi}fnT+{\phi})}\) for discrete. Leaving out the amplitude term, here is the continuous version, with the “imaginary” component shown in green

The discrete version \( = e^{j(2{\pi}fnT+{\phi})}\)

You can also do it based on \( = e^{j(2{\pi}fn/N +{\phi})}\).

Finally, you can use Scipy to write the data to a .wav file - here is 1 second at 440 Hz

comments powered by Disqus