Skip to content

Instantly share code, notes, and snippets.

@severak
Last active October 17, 2021 20:27
Show Gist options
  • Save severak/5649205b9f74ebf97194cd5f123a32c6 to your computer and use it in GitHub Desktop.
Save severak/5649205b9f74ebf97194cd5f123a32c6 to your computer and use it in GitHub Desktop.
Markov chain melody generator for Bespoke Synth
# Markov chain riff generator
# (c) Severak 2021
# feed it with notes and it will learn
# feed it with pulses and it will play new notes from those learned
from random import choice
class Markov:
def __init__(self):
self.prev = 0
self.chain = {}
# adds new note to internal memory
def add(self, note):
if self.prev not in self.chain:
self.chain[self.prev] = []
self.chain[self.prev].append(note)
self.prev = note
# generates new note
def next(self):
if self.prev==0:
raise Exception("Please feed some notes in before generating new ones.")
if self.prev in self.chain:
out = choice(self.chain[self.prev])
else:
out = choice(self.chain[0])
self.prev = out
return out
markov = Markov()
def on_note(n, v):
markov.add(n)
me.play_note(n, v)
def on_pulse():
n = markov.next()
me.play_note(n, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment