Advertisement
Guest User

Untitled

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