Create a Sine Wave
Learn how to create a sine wave and convert it into an audio file.
We'll cover the following
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:
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. is our old friend . is the Frequency. 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 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 .
The leftmost bit is reserved for the sign, leaving 15-bits. We’ll raise to the power of and then subtract one, as computers count from 0.
If we wanted a full-scale audio, we’d multiply it with . However, in that case we’d need an audio signal half as loud as a full-scale one to use an amplitude of .
Plotting an audio signal
Get hands-on with 1400+ tech skills courses.