Digital Sound & Music: Concepts, Applications, & Science, Chapter 2, last updated 6/25/2013
2.3.12 Modeling Sound in C++ under Linux
If you want to work at an even lower level of abstraction, a good environment for
experimentation is the Linux operating system using “from scratch” programs written in C++. In
our first example C++ sound program, we show you how to create sound waves of a given
frequency, add frequency components to get a complex wave, and play the sounds via the sound
device. This program is another implementation of the exercises in Max and MATLAB in
Sections 2.3.1 and 2.3.3. The C++ program is given in Program 2.4.
//This program uses the OSS library.
#include sys/ioctl.h //for ioctl()
#include math.h //sin(), floor(), and pow()
#include stdio.h //perror
#include fcntl.h //open, O_WRONLY
#include linux/soundcard.h //SOUND_PCM*
#include iostream
#include unistd.h
using namespace std;
#define TYPE char
#define LENGTH 1 //number of seconds per frequency
#define RATE 44100 //sampling rate
#define SIZE sizeof(TYPE) //size of sample, in bytes
#define CHANNELS 1 //number of audio channels
#define PI 3.14159
#define NUM_FREQS 3 //total number of frequencies
#define BUFFSIZE (int) (NUM_FREQS*LENGTH*RATE*SIZE*CHANNELS) //bytes sent to
audio device
#define ARRAYSIZE (int) (NUM_FREQS*LENGTH*RATE*CHANNELS) //total number of
#define SAMPLE_MAX (pow(2,SIZE*8 - 1) - 1)
void writeToSoundDevice(TYPE buf[], int deviceID) {
int status;
status = write(deviceID, buf, BUFFSIZE);
if (status != BUFFSIZE)
perror("Wrote wrong number of bytes\n");
status = ioctl(deviceID, SOUND_PCM_SYNC, 0);
if (status == -1)
perror("SOUND_PCM_SYNC failed\n");
int main() {
int deviceID, arg, status, f, t, a, i;
deviceID = open("/dev/dsp", O_WRONLY, 0);
if (deviceID 0)
perror("Opening /dev/dsp failed\n");
// working
arg = SIZE * 8;
status = ioctl(deviceID, SOUND_PCM_WRITE_BITS, &arg);
if (status == -1)
perror("Unable to set sample size\n");
status = ioctl(deviceID, SOUND_PCM_WRITE_CHANNELS, &arg);
Previous Page Next Page