Last changed on Wednesday, 28th July; at 6:46pm (UTC+1)

BEEP source


// BEEP.cpp : main project file.

#include "stdafx.h"
#include <iostream>
#include <cmath>

using namespace System;
using namespace std;

int A, As, B, C, Cs, D, Ds, E, F, Fs, G, Gs;
int getfreq(char *note);
int playnote(int Note = A, int Octave = 4, int duration = 1000);
void init();

int main(int argc, char *argv[]) {
    init();
    char Path[100];
    char again = 'y';
    FILE *fp;
    if (argc != 2) {
        cout << "No file specified!\nEnter file name: ";
        cin >> Path;
        if ((fp = fopen(Path, "r")) ==NULL) {
            cout << "Couldn't open file " << Path << '\n';
            Console::ReadLine();
            return 1;
        }
    }
    else {
        if ((fp = fopen(argv[1], "r")) ==NULL) {
            cout << "Couldn't open file " << argv[1] << '\n';
            Console::ReadLine();
            return 1;
        }
    }
    char note[3];
    char line[20];
    int octave;
    int duration;
    int pitch;
    while (again == 'y') {
        cout << "Playing.\n";
        while (!feof(fp)) {
            fgets(line, 20, fp);
            if (line != "\n") {
                sscanf(line, "%s%d%d", note, &octave, &duration);
                if ((pitch = getfreq(note)) == 0)
                    return 2;
                playnote(pitch, octave, duration);
            }
        }
        cout << "Again? ";
        cin >> again;
        rewind(fp);
    }
    fclose(fp);
    return 0;
}

void init()
{
    A = 55;
    As= 58;
    B = 61;
    C = 65;
    Cs= 69;
    D = 73;
    Ds= 78;
    E = 82;
    F = 87;
    Fs= 93;
    G = 98;
    Gs = 104;
    cout << "Note frequencies initialised.\n";
}

int getfreq(char *note) {
    if (!strcmp(note, "A"))
        return A;
    else if (!strcmp(note, "B"))
        return B;
    else if (!strcmp(note, "C"))
        return C;
    else if (!strcmp(note, "D"))
        return D;
    else if (!strcmp(note, "E"))
        return E;
    else if (!strcmp(note, "F"))
        return F;
    else if (!strcmp(note, "G"))
        return G;
    else if (!strcmp(note, "A+"))
        return As;
    else if (!strcmp(note, "C+"))
        return Cs;
    else if (!strcmp(note, "D+"))
        return Ds;
    else if (!strcmp(note, "F+"))
        return Fs;
    else if (!strcmp(note, "G+"))
        return Gs;
    else
        cout << "Error: unrecognised note!";
        return 0;
}

int playnote(int Note, int Octave, int duration) {
    int pitch = Note * pow((double)2, ((double)Octave - 1));
    Console::Beep(pitch, duration);
    return pitch;
}