Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Helper functions for music
- #include <cs50.h>
- #include <stdio.h>
- #include <string.h>
- #include <math.h>
- #include "helpers.h"
- // Converts a fraction formatted as X/Y to eighths
- int duration(string fraction)
- {
- return (8 / (fraction[2] - '0')) * (fraction[0] - '0');
- }
- // Calculates frequency (in Hz) of a note
- int frequency(string note)
- {
- int base_hz = 440;
- int semi = 0, octave = 0;
- // Set relative to 4th octave and account for accidental
- if(strlen(note) == 3)
- {
- octave = note[2] - '4';
- note[1] == '#' ? semi++ : semi--;
- }
- else
- {
- octave = note[1] - '4';
- }
- // Map note to semitone 0 to 11
- if(note[0] - 'C' < 0)
- {
- semi += note[0] == 'A' ? 9 : 11;
- }
- else
- {
- semi <<= (note[0] - 'C');
- if(semi > 5) semi--;
- }
- // Shift map relative to A4
- semi -= 9;
- octave < 0 ? (base_hz >>= abs(octave)) : (base_hz <<= octave);
- return base_hz * pow(2, semi / 12.0);
- }
- // Determines whether a string represents a rest
- bool is_rest(string s)
- {
- return *s == '\0' ? true : false;
- }
Add Comment
Please, Sign In to add comment