Digital Sound & Music: Concepts, Applications, & Science, Chapter 3, last updated 6/25/2013
47
3.3.5 Experimenting with Music in C++
Algorithm 3.2 is a C++ program analogous to the MATLAB program for generating scales. It
uses the same functions for writing to the sound device as used the last section of Chapter 2.
You can try your hand at a similar program by doing one of the suggested programming
exercises. The first exercise has you generate (or recognize) chords of seven types in different
keys. The second exercise has you generate equal tempered and just tempered scales and listen
to the result to see if your ears can detect the small differences in frequencies. Both of these
programs can be done in either MATLAB or C++.
//This program works under the OSS library
#include sys/ioctl.h //for ioctl()
#include math.h //sin(), floor()
#include stdio.h //perror
#include fcntl.h //open, O_WRONLY
#include linux/soundcard.h //SOUND_PCM*
#include iostream
#include stdlib.h
using namespace std;
#define LENGTH 1 //number of seconds
#define RATE 44100 //sampling rate
#define SIZE sizeof(short) //size of sample, in bytes
#define CHANNELS 1 // number of stereo channels
#define PI 3.14159
#define SAMPLE_MAX 32767 // should this end in 8?
#define MIDDLE_C 262
#define SEMITONE 1.05946
enum types {BACK = 0, MAJOR, MINOR};
double getFreq(int index){
return MIDDLE_C * pow(SEMITONE, index-1);
}
int getInput(){
char c;
string str;
int i;
while ((c = getchar()) != '\n' && c != EOF)
str += c;
for (i = 0; i str.length(); ++i)
str.at(i) = tolower(str.at(i));
if (c == EOF || str == "quit")
exit(0);
return atoi(str.c_str());
}
C++
Programming
Exercise:
Chords in
C++
C++
Programming
Exercise:
Equal vs Just
Tempered
Scales in C++
C++
Programming
Exercise:
Playing with
Music
Previous Page Next Page