-
Notifications
You must be signed in to change notification settings - Fork 410
/
helpers.c
83 lines (67 loc) Β· 1.52 KB
/
helpers.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Helper functions for music
#include <cs50.h>
#include <string.h>
#include <math.h>
#include "helpers.h"
// Converts a fraction formatted as X/Y to eighths
int duration(string fraction)
{
int numerator = fraction[0] - '0';
int denominator = fraction[2] - '0';
return numerator * (8 / denominator);
}
// Calculates frequency (in Hz) of a note
int frequency(string note)
{
int octave = note[strlen(note) - 1] - '0';
// Base frequency of A4 is 440hz
double freq = 440.0;
// Adjust for letter
switch (note[0])
{
case 'C':
freq /= pow(2.0, 9.0 / 12.0);
break;
case 'D':
freq /= pow(2.0, 7.0 / 12.0);
break;
case 'E':
freq /= pow(2.0, 5.0 / 12.0);
break;
case 'F':
freq /= pow(2.0, 4.0 / 12.0);
break;
case 'G':
freq /= pow(2.0, 2.0 / 12.0);
break;
case 'A':
break;
case 'B':
freq *= pow(2.0, 2.0 / 12.0);
break;
}
// Adjust for octave
if (octave > 4)
{
freq *= pow(2.0, octave - 4);
}
else if (octave < 4)
{
freq /= pow(2.0, 4 - octave);
}
// Adjust for accidental
if (note[1] == 'b')
{
freq /= pow(2.0, 1.0 / 12.0);
}
else if (note[1] == '#')
{
freq *= pow(2.0, 1.0 / 12.0);
}
return round(freq);
}
// Determines whether a string represents a rest
bool is_rest(string s)
{
return strlen(s) == 0;
}