Last active
September 25, 2017 01:48
-
-
Save prophetgoddess/8cd7f6605b30892ff66641ef54b90d71 to your computer and use it in GitHub Desktop.
Generates short piano compositions with cellular automata and saves them in MIDI format.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
#Command line utility to generate MIDI music intended for piano/piano-like synthesizers with cellular automata. | |
import random, click, pygame, time, sys, keyboard | |
import pygame.midi | |
from pygame.locals import * | |
from midiutil.MidiFile import MIDIFile | |
#pentatonic scales | |
MAJOR_SCALE = [60, 62, 64, 67, 69] | |
MINOR_SCALE = [60, 63, 65, 67, 70] | |
#function that takes in a cell index and the last row and outputs a value according to wolfram rule 90 | |
def evaluate(i, last_row): | |
left = "0" | |
middle = str(last_row[i]) | |
right = "0" | |
if i == 0: | |
left = str(random.randint(0, 1)) | |
else: | |
left = str(last_row[i - 1]) | |
if i == len(last_row) - 1: | |
right = str(random.randint(0, 1)) | |
else: | |
right = str(last_row[i + 1]) | |
state = left + middle + right | |
if state == "111": | |
return 0 | |
elif state == "110": | |
return 1 | |
elif state == "101": | |
return 0 | |
elif state == "100": | |
return 1 | |
elif state == "011": | |
return 1 | |
elif state == "010": | |
return 0 | |
elif state == "001": | |
return 1 | |
elif state == "000": | |
return 0 | |
#get the "sheet music". generates a 1d cellular automata over however many beats you want | |
def get_automata(voices, beats): | |
cells = [] | |
cells.append([]) | |
for i in range(voices): | |
cells[0].append(random.randint(0, 1)) | |
for i in range(1, beats): | |
cells.append([]) | |
row = cells[i] | |
last_row = cells[i - 1] | |
for i in range(voices): | |
row.append(evaluate(i, last_row)) | |
return cells | |
@click.command() | |
@click.option('--tempo', default=120, help="Tempo of the song.") | |
@click.option('--bars', default=12, help="Number of measures in the song. Has no effect in stream mode.") | |
@click.option('--scale', default="major", help="Major or minor scale.") | |
@click.option('--stream', default=False, help="Should we stream the output direct to midi?") | |
@click.option('--port', default=3, help="Device port that your synth is on. Only has effect in stream mode. I have no idea how to figure this out, just try numbers until it works.") | |
#where the magic happens | |
def make_song(tempo, bars, scale, stream, port): | |
pitches = [] | |
if scale == 'major': | |
pitches = MAJOR_SCALE | |
elif scale == 'minor': | |
pitches = MINOR_SCALE | |
if not stream: | |
mf = MIDIFile(1, adjust_origin=True) | |
beats = bars * 4 #we're working in 4/4 time here | |
automata = get_automata(len(pitches), beats) | |
mf.addTrackName(0, 0, "Lead") | |
mf.addTempo(0, 0, tempo) | |
#for every note in the scale, figure out the pattern of note lengths. | |
for i in range(len(pitches)): | |
beat = 0 | |
note_length = 0 | |
while beat < beats: | |
if automata[beat][i] == 1: | |
note_length += 1 | |
elif (automata[beat][i] == 0 or beat == beats) and note_length > 0: | |
mf.addNote(0, 0, pitches[i], beat - note_length, note_length, 100) | |
note_length = 0 | |
beat += 1 | |
#write to a file. | |
file_name = 'song-{}.mid'.format(random.randint(1000, 9999)) | |
with open(file_name, 'wb') as f: | |
mf.writeFile(f) | |
print("Saved as", file_name) | |
else: | |
#pygame is, no joke, the best way to output midi from your computer to a synthesizer (as far as i know) | |
pygame.init() | |
pygame.midi.init() | |
midi_out = pygame.midi.Output(port, 0) | |
cells = [] | |
#get our seed row | |
cells.append([]) | |
for v in range(len(pitches)): | |
cells[0].append(random.randint(0, 1)) | |
i = 0 | |
new_time = time.time() * 1000 | |
old_time = time.time() * 1000 | |
timer = 0 | |
delay = 1/(tempo/60) | |
run = True | |
print("Push escape to end playback.") | |
while run: | |
pygame.event.pump() | |
old_time = new_time | |
new_time = time.time() * 1000 | |
delta_time = (new_time - old_time) / 1000 | |
timer += delta_time | |
try: | |
if keyboard.is_pressed('escape'): | |
run = False | |
except: | |
pass | |
#every time there's a new beat, turn on and off notes as appropriate | |
if timer >= delay: | |
timer = 0 | |
for v in range(len(pitches)): | |
if cells[i][v] == 1: | |
midi_out.note_on(pitches[v], 100) | |
else: | |
midi_out.note_off(pitches[v]) | |
i += 1 | |
cells.append([]) | |
row = cells[i] | |
last_row = cells[i - 1] | |
for v in range(len(pitches)): | |
row.append(evaluate(v, last_row)) | |
#make sure we turn off all the notes so it doesn't keep playing without input | |
for v in range(len(pitches)): | |
midi_out.note_off(pitches[v]) | |
pygame.midi.quit() | |
sys.exit() | |
if __name__ == '__main__': | |
make_song() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Copyright (c) 2017 Emma Lugo | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment