Skip to content

Instantly share code, notes, and snippets.

@EdThePro101
Created January 3, 2021 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdThePro101/001dba3c28c7f92bf83a73a571c0c4b6 to your computer and use it in GitHub Desktop.
Save EdThePro101/001dba3c28c7f92bf83a73a571c0c4b6 to your computer and use it in GitHub Desktop.
This is a very simple melody generator made in C.
// Copyright (c) 2021 Edwin Pratt
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Compile with
// gcc -Wall -Werror -Wextra -o melody-gen melody-gen.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Next note prediction.
// Should we step up or down, or leap up or down, or repeat the note?
// When leaping, we'll use a different variable called "leap_size" that ranges from 2-3 whole tones.
int available_note_preds = 5;
typedef enum _next_note_pred_t {
STEP_UP,
STEP_DOWN,
LEAP_UP,
LEAP_DOWN,
REPEAT
} next_note_pred_t;
// Print the note
void print_curr_note(int curr_note) {
char notes[7] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
printf("%c ", notes[curr_note % 7]);
}
int main() {
srand(time(0));
int bar_count = 2;
int num_notes_in_bar = 4;
int num_whole_notes = 7;
int leap_size = 0;
int curr_note = -1;
for (int i = 0; i < bar_count * num_notes_in_bar; ++i) {
// Get a prediction
next_note_pred_t note_pred = 0 + (rand() % available_note_preds);
// If no note was chosen before, skip this step and generate a random note.
if (curr_note != -1) {
switch (note_pred) {
case STEP_UP:
// Step up
curr_note += 1;
break;
case STEP_DOWN:
// Step down
curr_note -= 1;
break;
case LEAP_UP:
// Leap up
leap_size = 2 + (rand() % 2); // 2 + [0, 1, 2] = [2, 3, 4]
curr_note += leap_size;
break;
case LEAP_DOWN:
// Leap down
leap_size = 2 + (rand() % 2); // 2 + [0, 1, 2] = [2, 3, 4]
curr_note -= leap_size;
break;
case REPEAT:
// Note stays the same
curr_note = curr_note;
break;
}
} else {
curr_note = 0 + (rand() % num_whole_notes);
}
print_curr_note(curr_note);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment