Created
July 23, 2018 06:31
-
-
Save bradleygrant/cde14ea5944eb656c5ff248099ce711e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Helper functions for music | |
#include <cs50.h> | |
#include <math.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include "helpers.h" | |
int findOctave(char); | |
// Converts a fraction formatted as X/Y to eighths | |
int duration(string fraction) | |
{ | |
int num = atoi(&fraction [0]); | |
int den = atoi(&fraction [2]); | |
int durvalue = num * 8 / den; | |
return durvalue; | |
} | |
// Calculates frequency (in Hz) of a note | |
int frequency(string note) | |
{ | |
// TODO | |
int freqvalue = 440; // count notes from A4 = 440 Hz | |
char rootnote = note [0]; | |
int semitones = 0; // set starting note = A4 | |
int octave = 4; | |
bool isFlat = false; | |
bool isSharp = false; | |
char sf = note [1]; | |
// test for sharp/flat, then find the octave named in the string | |
if (sf == '#') | |
{ | |
isSharp = true; | |
octave = findOctave(note [2]); | |
} | |
else if (sf == 'b') | |
{ | |
isFlat = true; | |
octave = findOctave(note [2]); | |
} | |
else | |
{ | |
octave = findOctave(note [1]); | |
} | |
// use rootnote, sharp/flat, and octave to calculate semitone distance | |
switch (rootnote) | |
{ | |
case 'A' : | |
// do nothing | |
break; | |
case 'B' : | |
semitones = semitones + 2; | |
break; | |
case 'C' : | |
semitones = semitones - 9; | |
break; | |
case 'D' : | |
semitones = semitones - 7; | |
break; | |
case 'E' : | |
semitones = semitones - 5; | |
break; | |
case 'F' : | |
semitones = semitones - 4; | |
break; | |
case 'G' : | |
semitones = semitones - 2; | |
break; | |
} | |
if (isSharp) | |
{ | |
semitones++; | |
} | |
if (isFlat) | |
{ | |
semitones--; | |
} | |
// adjust for octave | |
semitones = semitones + ((octave - 4) * 12); | |
// calculate frequency value | |
double freq = 440 * pow(2.0, ((double) semitones / 12.0)); | |
freqvalue = (int) round(freq); | |
return freqvalue; | |
} | |
// Used by frequency to determine octave represented by a one-character string containing a number | |
int findOctave(char octletr) | |
{ | |
int coctave = atoi(&octletr); | |
return coctave; | |
} | |
// Determines whether a string represents a rest | |
bool is_rest(string s) | |
{ | |
if (strcmp(s, "") == 0) | |
{ | |
return true; | |
} | |
else | |
{ | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment