Miscellaneous C++: Simple Sounds

Simple Sounds

In this video, we demonstrate how to use simple sounds to create music. The two functions that we use are Beep() and Sleep(), which are declared in the “windows.h” file. Our first example code makes one call to each function:

#include <windows.h>

int main() {

    Beep(440, 500);
    Sleep(500);

    return 0;
}

The Beep() function takes a frequency parameter 440 Hz and a duration parameter 500ms, and the Sleep() function simply takes a duration parameter 500ms. The Beep() function plays a tone at the give frequency (440Hz = A just above Middle C) and the Sleep() function plays nothing. So, we can combine these functions to play notes (Beep) or rests (Sleep) and create music.

The small program shown above plays a single beep. However, we can string notes together to play an entire song.

In our second example, we create the classes CNote and CMelody, which allow us to put together a sequence of notes to create a song. Since it is Christmas time, we have added the notes for "Silent Night". Merry Christmas!

Above, we have a table of conversions for three octaves from frequencies to notes. The value 262Hz is the Middle C. Along with our classes for creating notes and melodies, these frequency conversions can be used to create music. The table below shows conversions between various note and rest durations and milliseconds.

The table for duration is set by the first value in our duration enumeration, and it can be changed easily by resetting this value. Changing the duration of the first value will change the tempo of the music, making play faster or slower.

This video demonstrates only very limited sound capabilities. However, we can and will play much more sophisticated music and sound in later lessons. Then, we will be able to alter timbre, as well as frequency and duration, and put together multiple melodies to create harmonies.