Create a Sine Wave

Learn how to create a sine wave and convert it into an audio file.

In this lesson, we’ll learn how to create a sine wave and save it as a wav file. Before that, let’s go over some basic theory that you should know.

Some definitions

Frequency: Frequency is the number of times a sine wave repeats a second. In this lesson, we’ll use a frequency of 1KHz.

Sampling rate: Most real-world signals are analogs, while computers are digital. So we need a converter to convert our analog signal into a digital representation of that signal.However, the critical thing to understand here is the sampling rate, which is the number of times the converter takes a sample of the analog signal in a second.

Now, the sampling rate doesn’t matter as much since we’re doing everything digitally, but it’s needed for our sine wave formula. We’ll use a value of 48000, which is the value used in professional audio equipment.

Sine wave formula:

y(t)=Asin(2pift)y(t) = A * sin(2 * pi * f * t)

y(t)y(t) is the y-axis sample we want to calculate for the x-axis sample t. A is the amplitude. We’ll come back to that later. pipi is our old friend π=3.14159\pi = 3.14159. ff is the Frequency. tt is our sample. Since we need to convert it to digital, we’ll divide it by the sampling rate.

Amplitude: Mostly, they choose a random value for AA like 11. But this won’t work for us. The sine wave that we generate will be in floating-point, and, while that will be good enough for drawing a graph, it won’t work when we write into a file. This is because we’re dealing with integers. If we look at wave files, they’re written as 16-bit short integers. If we write a floating-point number, it will not be represented correctly.

To get around this, we’ll have to convert our floating-point number to a fixed point. We can do this by multiplying it with a fixed constant. How do we calculate this continuous? Well, the maximum value of a signed 16-bit number is 32767(2151)32767 (2 ^{15} - 1).

The leftmost bit is reserved for the sign, leaving 15-bits. We’ll raise 22 to the power of 1515 and then subtract one, as computers count from 0.

If we wanted a full-scale audio, we’d multiply it with 3276732767. However, in that case we’d need an audio signal half as loud as a full-scale one to use an amplitude of 1600016000.

Plotting an audio signal

Get hands-on with 1400+ tech skills courses.