Lesson goal: Play the sum of some sines

Previous: Compose music | Home | Next: Play a chirp

As mentioned in this lesson, sound is generated by making a speaker diaphram pulse inward and outward. For this reason, the mathematical function $sin(x)$ is often use to generate signals for a speaker, since the $\sin$ function goes up and down, which can be thought of as an "in and out" for a speaker.

Here we introduce a function called play_sines() that will play the results of one or more sine-waves added together, out to your speaker. What is important for sound is the amplitude of the sine-wave, (or how loud it'll be), and it's frequency (or how quickly the speaker diaphram is pushed in and out). Amplitudes are between 0 and 1 and frequencies are generally between 100 and 25,000.

If you want to play one sine-wave, it'll resemble $A\sin(2\pi f t)$, where $A$ is the amplitude and $f$ is the frequency. So if you call play_sines() as play_sines({1,500},3), a 500 Hz frequency will be played at full amplitude for 3 seconds. Playing the two sines at full and half-amplitude of 500 Hz and 1000 Hz, for 3 seconds, would be play_sines({1,500,0.5,1000},3).

play_sines({amp1,freq1,amp2,freq2,...,ampn,freqn},duration)
Move the mouse over a dotted box for more information.

Mathematically, what gets played is $\Sigma A_n\sin(2\pi f_n t)$, where $A_n$ is the amplitude of the nth sin-wave and $f_n$ is its frequency.

Now you try. See what cool sounds you can create by adding a bunch of sines together!

Type your code here:


See your results here:

The default code will play a sine with a frequency of 1209 and 697, both at full amplitude. This should sound like a "1" key pressed on a touch-tone phone. And, if you hold your phone near the computer speaker, it might actually trigger it into dialing a "1."

Notice that the amplitude/frequency parameters are an array of numbers (hence the { and } surrounding them. See Example 1 for playing an array of sin waves with random ferquencies.

Try playing to closely spaced frequencies like play_sines({1,600,1,605},3) to hear "beats." Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.