Small utility library for MIDI functions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.0 KiB

  1. #include "midi-utils.h"
  2. char* MIDI_GetNoteName(unsigned char midi_note) {
  3. static const char* pitch_names[] = {
  4. "C",
  5. "C#",
  6. "D",
  7. "D#",
  8. "E",
  9. "F",
  10. "F#",
  11. "G",
  12. "G#",
  13. "A",
  14. "A#",
  15. "B"
  16. };
  17. const unsigned char pitch_class = midi_note % 12;
  18. const unsigned char octave = midi_note / 12;
  19. static char note_name[8];
  20. sprintf(note_name, "%s%u", pitch_names[pitch_class], octave);
  21. return note_name;
  22. }
  23. unsigned char MIDI_GetNoteFromName(const char* name) {
  24. char name_copy[8];
  25. strcpy(name_copy, name);
  26. _strlwr(name_copy);
  27. unsigned char octave = 0;
  28. unsigned char has_accidental = name_copy[1] == '#' || name_copy[1] == 'b';
  29. unsigned char octave_start = has_accidental ? 2 : 1;
  30. unsigned char pitch_class;
  31. char octave_offset = 0;
  32. for (unsigned char i = octave_start; '0' <= name_copy[i] && name_copy[i] <= '9'; i += 1) {
  33. octave *= 10;
  34. octave += name_copy[i] - '0';
  35. }
  36. if (strstr(name_copy, "c#") || strstr(name_copy, "db")) {
  37. pitch_class = 1;
  38. } else if (strstr(name_copy, "d#") || strstr(name_copy, "eb")) {
  39. pitch_class = 3;
  40. } else if (strstr(name_copy, "fb")) {
  41. pitch_class = 4;
  42. } else if (strstr(name_copy, "e#")) {
  43. pitch_class = 5;
  44. } else if (strstr(name_copy, "f#") || strstr(name_copy, "gb")) {
  45. pitch_class = 6;
  46. } else if (strstr(name_copy, "g#") || strstr(name_copy, "ab")) {
  47. pitch_class = 8;
  48. } else if (strstr(name_copy, "a#") || strstr(name_copy, "bb")) {
  49. pitch_class = 10;
  50. } else if (strstr(name_copy, "cb")) {
  51. pitch_class = 11;
  52. octave_offset = -1;
  53. } else if (strstr(name_copy, "b#")) {
  54. pitch_class = 0;
  55. octave_offset = 1;
  56. } else if (strstr(name_copy, "c")) {
  57. pitch_class = 0;
  58. } else if (strstr(name_copy, "d")) {
  59. pitch_class = 2;
  60. } else if (strstr(name_copy, "e")) {
  61. pitch_class = 4;
  62. } else if (strstr(name_copy, "f")) {
  63. pitch_class = 5;
  64. } else if (strstr(name_copy, "g")) {
  65. pitch_class = 7;
  66. } else if (strstr(name_copy, "a")) {
  67. pitch_class = 9;
  68. } else if (strstr(name_copy, "b")) {
  69. pitch_class = 11;
  70. } else {
  71. return 255u;
  72. }
  73. return ((octave * 12) + octave_offset) + pitch_class;
  74. }