Building an Audio Track from Raw Samples

As I’ve said many times before: movies have tracks, tracks have media, media have samples. But what are these samples? In the case of sound, they indicate how much voltage should be applied to a speaker at an instant of time. By itself, a sample is meaningless, but as a speaker is repeatedly excited and relaxed, it creates waves of sound that move through the air and can be picked up by the ear.

So, why would you want to do this? One plausible scenario is that you have code that generates this uncompressed pulse code modulation (PCM) data, like a decoder for some format that QuickTime doesn’t support. By writing the raw samples to an empty movie, you can expose it to QuickTime and then play it, export it to QT-supported formats, and use other QuickTime-related functions.

How do I do that?

SoundMedia inherits an addSample( ) method from the Media class. This can be used to pack samples into a Media, which in turn can be added to a Track, which then can be added to a Movie.

But what values do you provide to create an audible sound? The example shown in Example 7-5 creates a square wave at a constant frequency. A square wave is one in which the voltage is either fully on or completely off. To create a 1000-hertz (Hz) tone, you write samples to alternate between full voltage and zero voltage, 1,000 times per second. Figure 7-4 shows a graph of sample values for the square wave.

Note

Run this example with ant run-ch07-audiosamplebuilder

Get QuickTime for Java: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.