Guest User

Untitled

a guest
Mar 17th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. // Helper functions for music
  2.  
  3. #include <cs50.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <math.h>
  7.  
  8. #include "helpers.h"
  9.  
  10. // Converts a fraction formatted as X/Y to eighths
  11. int duration(string fraction)
  12. {
  13. return (8 / (fraction[2] - '0')) * (fraction[0] - '0');
  14. }
  15.  
  16. // Calculates frequency (in Hz) of a note
  17. int frequency(string note)
  18. {
  19. int base_hz = 440;
  20. int semi = 0, octave = 0;
  21.  
  22. // Set relative to 4th octave and account for accidental
  23. if(strlen(note) == 3)
  24. {
  25. octave = note[2] - '4';
  26. note[1] == '#' ? semi++ : semi--;
  27. }
  28. else
  29. {
  30. octave = note[1] - '4';
  31. }
  32.  
  33. // Map note to semitone 0 to 11
  34. if(note[0] - 'C' < 0)
  35. {
  36. semi += note[0] == 'A' ? 9 : 11;
  37. }
  38. else
  39. {
  40. semi <<= (note[0] - 'C');
  41. if(semi > 5) semi--;
  42. }
  43.  
  44. // Shift map relative to A4
  45. semi -= 9;
  46.  
  47. octave < 0 ? (base_hz >>= abs(octave)) : (base_hz <<= octave);
  48.  
  49. return base_hz * pow(2, semi / 12.0);
  50. }
  51.  
  52. // Determines whether a string represents a rest
  53. bool is_rest(string s)
  54. {
  55. return *s == '\0' ? true : false;
  56. }
Add Comment
Please, Sign In to add comment