Advertisement
Normantas

CS50 Exercise Music | Solution by Normantas

Dec 22nd, 2018
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.77 KB | None | 0 0
  1. // Helper functions for music
  2.  
  3. #include <cs50.h>
  4. #include <math.h>
  5. #include "helpers.h"
  6.  
  7. int scaleCal(int _f, char _scale) //4+
  8. {
  9.     if (_scale == '#'){
  10.         _f = round(_f * pow(2, 1/12));
  11.     }
  12.     else if(_scale == 'b'){
  13.         _f = round(_f / pow(2, 1/12));
  14.     }
  15.     return _f;
  16. }
  17.  
  18. int letterMov(char l, int _f) //2
  19. {
  20.     if(l == 'A')
  21.         _f = 440;
  22.     if(l == 'B')
  23.         _f = round(_f * pow(2, 2/12));
  24.     if(l == 'G')
  25.         _f = round(_f / pow(2, 2/12));
  26.     if(l == 'F')
  27.         _f = round(_f / pow(2, 4/12));
  28.     if(l == 'E')
  29.         _f = round(_f / pow(2, 5/12));
  30.     if(l == 'D')
  31.         _f = round(_f / pow(2, 7/12));
  32.     if(l == 'C')
  33.         _f = round(_f / pow(2, 9/12));
  34.     return _f;
  35. }
  36.  
  37. int octaveFreq(int oct, int _f) //3
  38. {
  39.     double a = oct - 4;
  40.     if (oct > 4)
  41.     {
  42.         _f = _f * pow(2, a);
  43.     }
  44.     else if(oct < 4 )
  45.     {
  46.         _f = round(_f / pow(2, a));
  47.     }
  48.     return _f;
  49. }
  50.  
  51. char octaveCheck(char a, char b) //1
  52. {
  53.      if(a == '#' || a == 'b'){ //Checks for # or b;
  54.         return b;
  55.     }
  56.     else{
  57.         return a;
  58.     }
  59. }
  60.  
  61. // Converts a fraction formatted as X/Y to eighths
  62. int duration(string fraction)
  63. {
  64.     int up = (int)fraction[0];
  65.     int down = (int)fraction[2];
  66.     return up * 8 / down;
  67. }
  68.  
  69. // Calculates frequency (in Hz) of a note
  70. int frequency(string note)
  71. {
  72.     int octave, f = 0; char letter, scale;
  73.     octave = octaveCheck(note[1],note[2]);
  74.     letter = note[0];
  75.     scale = note[1];
  76.     f = letterMov(letter, f);
  77.     f = octaveFreq(octave, f);
  78.     f = scaleCal(f, scale);
  79.     return f;
  80. }
  81.  
  82. // Determines whether a string represents a rest
  83. bool is_rest(string s)
  84. {
  85.    if(s[0] == '\0')
  86.    {
  87.        return true;
  88.    }
  89.    else
  90.    {
  91.         return false;
  92.    }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement