Digital Audio Waveforms


Digital Audio Waveforms

Hope
Hello everyone, and welcome to Coding Adventures. Today we're exploring sound computationally, starting with something wonderfully physical: talking. Vibrating vocal folds, shaped by the mouth and tongue, create pressure waves in the air. Those waves vibrate a microphone membrane, move a coil across a magnet, induce a voltage, and become measurements that a computer stores as audio samples.

Anna
So a sound file is ultimately a sequence of measurements of that changing microphone voltage?

Hope
Exactly. The computer measures the signal thousands of times per second, storing numerical sample values. The first task is to open a WAV file and turn those stored values back into something we can inspect.

Anna
The WAV format is a useful place to begin because its structure is fairly approachable. The file starts with identifying bits that should spell out RIFF and WAVE. If they do not, the file is not in the expected format.

Hope
After that, the parser moves through chunks. Each chunk has a name and a size, so the code can record the chunk's location in a lookup table and skip forward by the stated size. That makes it easy to jump directly to the format chunk and the data chunk.

Anna
The format chunk contains metadata we need before interpreting the samples: whether the recording is mono or stereo, the sample rate, and the number of bits used for each sample.

Hope
Then the data chunk supplies the actual audio bytes. Since samples can have different formats, the parser repeatedly reads the number of bytes specified for one sample and converts them into a floating-point value. The value is divided by a normalization factor—the largest value that this number of bytes can represent—so the samples fit into a convenient range from negative one to positive one.

Anna
That conversion needs to handle signed values correctly. One slightly awkward case is 24-bit audio, because there is no standard built-in type for a three-byte integer, so bit manipulation is needed to interpret negative numbers properly.

Hope
Once the samples are converted, the program packages the sample array and sample rate into a signal object. For a recording with just under forty thousand samples at forty-eight thousand samples per second, the duration is the number of samples divided by the sample rate—about zero point eight seconds.

Anna
And visualizing those samples makes the representation concrete. One plot can show each sample as a point, with time on the horizontal axis and signal value, proportional to microphone voltage, on the vertical axis. Drawing connected or vertical lines instead gives the familiar waveform appearance.

Hope
It is striking that a complicated voice can be represented by nothing more than this long list of numbers. To hear it again, Unity provides an audio-read callback that periodically gives the program an empty block. While samples remain, the code fills that block, sends it to the sound card, and the speakers or headphones vibrate according to those values.

Anna
The same general process works in reverse for playback: numerical samples drive the hardware, the hardware creates pressure waves, and we perceive those waves as sound.

Hope
The project then tried to simulate those pressure waves in a two-dimensional fluid simulation. The fluid was adjusted to behave more like air by turning off gravity and lowering the target density. Instead of drawing individual particles, the visualization calculated density at each texture cell, because density is closely related to pressure.

Anna
That density is essentially a smoothed sum of the particles within a small radius around a location. Coloring each cell according to that density reveals pressure-like waves moving through the simulated fluid.

Hope
The simulation was initially unstable. Viscosity was still enabled from the earlier water setup, and the particle count had been increased from roughly fifteen thousand to seventy-five thousand. Those settings produced strange bubbles, but reducing the problematic effects made the simulation more stable.

Anna
A rectangular obstacle could then act as a speaker membrane. Its position was moved back and forth according to the input audio. Since the original audio consists of discrete samples, the simulation linearly interpolated between neighboring samples so the membrane moved more smoothly instead of jumping at every sample.

Hope
A simulated microphone measured the density at a chosen location, subtracted the fluid's rest density, and multiplied the result by an arbitrary constant to create a pressure value. Those pressure values were saved as another recording.

Anna
At ordinary simulation speed, that failed dramatically. In four seconds the simulation managed only about twelve hundred steps, so it captured only about twelve hundred pressure values, while the original four-second audio contained around one hundred ninety-two thousand samples.

Hope
Slowing the speaker's time step helped. When one second of input audio took one hundred seconds of simulation time, the recorded sound became barely understandable. Slowing it further—eventually to fifteen minutes of simulation for each second of input—allowed the fluid to react more adequately. After waiting about an hour for a four-second clip, the result was recognizable, though crackly.

Anna
That experiment shows an important practical issue: a physical simulation needs enough updates to respond to the changing signal. If the simulated medium cannot react between meaningful changes in the input, the recorded result loses most of the sound.

Hope
The WAV code was also extended to save files, not just read them. Reversing the order of the samples creates reversed audio, while changing the sample rate attached to the same samples changes the playback speed.

Anna
Playing the samples at a lower stated sample rate stretches the waveform and makes it slower. Playing them at a higher rate compresses it and makes it faster. In both cases the pitch changes too, because stretching or compressing the waveform changes its frequencies.

Hope
That leads to the central question: how can we identify the frequencies that make up a sound? Real speech is complicated, so the investigation began with a synthetic signal. To generate a pure tone, the program calculates time for each sample, forms an angle equal to time multiplied by two pi and the chosen frequency, and takes the sine or cosine of that angle.

Anna
Two pi is the constant tau in the explanation, and it represents one full rotation in radians. A point traveling around a unit circle completes that rotation after traveling about six point two eight units. Sine and cosine provide the point's vertical and horizontal coordinates.

Hope
Multiplying time by tau makes one trip around the circle take one second. Multiplying by the frequency changes how many trips occur per second. That is why a one-hertz signal completes one oscillation each second, while a four-hertz signal completes four.

Anna
In the sound interpretation, the waveform represents air pressure over time at a particular location. Peaks are compressions, where air molecules are more tightly bunched, and troughs are rarefactions, where they are more spread out.

Hope
A single pure tone is limited, so the signal generator was extended to combine multiple frequency components. Each component stores a frequency, amplitude, and phase. The generated sample is the sum of the components' sine or cosine contributions.

Anna
Amplitude controls the strength of a component. Phase shifts where its wave begins, effectively shifting it left or right. Combining waves with different frequencies, phases, and amplitudes produces more complex sounds, even though each individual component is simple.

Hope
The desired reverse-engineering tool is the discrete Fourier transform, or DFT. It takes a finite collection of samples and tests how strongly the signal matches different frequencies. The goal is to recover the component frequencies, their amplitudes, and their phases.

Anna
The geometric visualization makes the DFT idea intuitive. For every sample, choose a test angle that progresses from zero to tau, rotate around a circle, and multiply that test point by the corresponding sample value. The resulting sample points are drawn as a trail.

Hope
When the test frequency matches a component in the signal, its sample points form an offset circle. When it does not match, the points spread around the circle and largely cancel out. The average position of all the sample points—the sample center—reveals this difference.

Anna
If the test frequency is not present, the sample center stays at or returns to zero. If it is present, the center is displaced from the origin. Other frequencies do not change that average in the ideal integer-frequency examples because their contributions cancel.

Hope
The distance from the origin tells us about amplitude. In the visualization, the sample center sits in the middle of the offset circle, so its distance is half the component's strength; doubling that distance gives the amplitude. The angle of the sample center gives the phase.

Anna
For a signal containing frequencies three, five, and nine, testing frequency three displaced the center, while testing unrelated frequencies left it near zero. Testing five showed a component with amplitude zero point four and a phase offset by half a turn, and testing nine revealed the highest component.

Hope
Plotting the center's distance over a range of test frequencies produces peaks at the frequencies present in the signal. Fractional frequencies create a complication: if the signal does not complete a whole number of cycles in the recording window, its start and end do not line up, and energy spills into nearby tested frequencies. This effect is called spectral leakage.

Anna
The recording duration controls the frequency resolution. A one-second recording naturally lines up with integer frequencies. A two-second recording can align with frequencies spaced by one-half hertz, because one point five hertz completes three cycles. A ten-second recording allows steps of one-tenth of a hertz.

Hope
The sample rate controls a different thing: the highest frequency we can detect. The Nyquist-Shannon sampling theorem says the sampling rate must be at least twice the highest frequency in the signal to avoid aliasing.

Anna
Aliasing happens when samples are too far apart and skip over important peaks and valleys. A high-frequency wave can then appear to be a much lower-frequency wave, taking on a false identity. Sampling a signal at exactly twice its frequency can also be unlucky if the sample phase makes every value line up in an uninformative way, so sampling above the Nyquist rate is safer.

Hope
For human audio, hearing extends to roughly twenty kilohertz, suggesting a minimum around forty kilohertz. Frequencies above that limit can still create aliasing distortions, so filters are used before sampling to remove them. Because real filters are not perfect, standardized rates such as forty-four point one and forty-eight kilohertz include some extra margin.

Anna
That means the maximum frequency tested by the DFT should not be hardcoded as twenty kilohertz. It is determined by the signal's sample rate: the highest meaningful frequency is half the sample rate.

Hope
The practical DFT implementation follows that idea. The number of detectable frequency bins is the maximum frequency multiplied by the recording duration, which simplifies to half the number of samples. The spacing between bins is one divided by the duration, or equivalently the sample rate divided by the number of samples.

Anna
For every bin, the algorithm calculates the sample center, extracts amplitude and phase from that center, determines the corresponding frequency, and stores the result in a spectrum. There are two special amplitude cases: at zero frequency and at exactly half the sample rate, the usual doubling is not needed.

Hope
The transform was tested by sampling a synthetic signal at the minimum rate just above twice its highest frequency, extracting its spectrum, and rebuilding the signal by adding the recovered waves. The reconstructed curve matched the original, and increasing the sample rate produced the expected matching result.

Anna
On real speech, the reconstruction could be watched as the recovered frequency components were added together. The amplitude spectrum showed that frequencies above about five kilohertz had extremely small amplitudes in that recording.

Hope
Sorting the components by amplitude demonstrated how much information different numbers of frequencies preserve. The top five produced only a low hum, the top fifty sounded more varied, and around two hundred fifty began to suggest speech. With seven hundred fifty and fifteen hundred components the words became clearer, while five thousand gave very clear speech with some hum and hiss.

Anna
Using one hundred thousand components made the reconstruction effectively indistinguishable from the original. So the spectrum provides a way not only to analyze sound, but also to approximate it using only the most influential frequency components.

Hope
The direct DFT did eventually work, but it was painfully slow, especially when analyzing and reconstructing audio. That sets up the next step: implementing the fast Fourier transform, or FFT, a more efficient algorithm for carrying out the same kind of frequency analysis.

Anna
So the journey went from vocal pressure waves, to microphone voltages, to WAV bytes, to plotted and replayed samples, then to simulated air, synthesized tones, geometric frequency detection, sampling theory, spectral leakage, and finally a working—if slow—DFT.

Hope
And the key idea tying it all together is that a complex sound can be understood as a combination of simpler waves. Once those frequency components, amplitudes, and phases can be extracted, we gain tools for reconstructing, analyzing, and manipulating the original audio.

Ask anything
We've read this whole study set, so questions about it get the best answers.