Digital Sound & Music: Concepts, Applications, & Science, Chapter 2, last updated 6/25/2013
53
if (status == -1)
perror("Unable to set number of channels\n");
arg = RATE;
status = ioctl(deviceID, SOUND_PCM_WRITE_RATE, &arg);
if (status == -1)
perror("Unable to set sampling rate\n");
a = 1;
for (i = 0; i NUM_FREQS; ++i) {
switch (i) {
case 0:
f = 262;
break;
case 1:
f = 330;
break;
case 2:
f = 392;
break;
}
for (t = 0; t ARRAYSIZE/NUM_FREQS; ++t) {
buf[t + ((ARRAYSIZE / NUM_FREQS) * i)] = floor(a *
sin(2*PI*f*t/RATE));
}
}
writeToSoundDevice(buf, deviceID);
}
Program 2.4 Adding sine waves and sending sound to sound device in C++
To be able to compile and run a program such as this, you need to install a sound library
in your Linux environment. At the time of the writing of this chapter, the two standard low-level
sound libraries for Linux are the OSS (Open Sound System) and ALSA (Advanced Linux Sound
Architecture). A sound library provides a software interface that allows your program to access
the sound devices, sending and receiving sound data. ALSA is the newer of the two libraries and
is preferred by most users. At a slightly higher level of abstraction are PulseAudio and Jack,
applications which direct multiple sound streams from their inputs to their outputs. Ultimately,
PulseAudio and Jack use lower level libraries to communicate directly with the sound cards.
Program 2.4 uses the OSS library. In a program such as this, the sound
device is opened, read from, and written to in a way similar to how files are
handled. The sample program shows how you open /dev/dsp, an interface to the
sound card device, to ask this device to receive audio data. The variable
deviceID serves as an ID of the sound device and is used as a parameter
indicating the size of data to expect, the number of channels, and the data rate.
We‟ve set a size of eight bits (one byte) per audio sample, one channel, and a
data rate of 44,100 samples per second. The significance of these numbers will
be clearer when we talk about digitization in Chapter 5. The buffer size is a
product of the sample size, data rate, and length of the recording (in this case,
three seconds), yielding a buffer of 44,100 * 3 bytes.
The sound wave is created by taking the sine of the appropriate frequency (262 Hz, for
example) at 44,100 evenly-spaced intervals for one second of audio data. The value returned
from the sine function is between 1 and 1. However, the sound card expects a value that is
C++
Programming
Exercise:
Writing to an
Audio Device
Previous Page Next Page