Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #RANDOM "MUSIC" GENERATOR
- #Thanks to http://www.cyber-omelette.com/2017/01/markov.html for help with markov implementation.
- import random
- #so i can keep note info in one place
- class note:
- def __init__(self, pitch='0', start='0', length='0'):
- self.pitch = pitch
- self.start = start
- self.length = length
- def readdata():
- with open("data.txt") as rawdata:
- #converts the data into something more usable.
- #the data becomes a nested list. each item in the first list represents a note.
- #each item in the second list represents (in order) the pitch, start, and length of the note.
- data = str(rawdata.read()).split('\n')
- for i in range(len(data)):
- data[i] = data[i].split(' ')
- return data
- def makepitchrule(data):
- #for now I'll only look one note back for reference
- #the pitch and length will be calculated seperately. Start can be ignored.
- #create reference for pitch of notes
- location = 1
- pitchrule = {}
- for pitch in data[location:]:
- key = data[location - 1][0]
- if key in pitchrule:
- pitchrule[key].append(pitch[0])
- else:
- pitchrule[key] = [pitch[0]]
- location += 1
- return pitchrule
- def makelengthrule(data):
- #do the exact same thing, but with length
- #there's probably an easy way to combine these that I'm overlooking
- location = 1
- lengthrule = {}
- for length in data[location:]:
- key = data[location - 1][2]
- if key in lengthrule:
- lengthrule[key].append(length[2])
- else:
- lengthrule[key] = [length[2]]
- location += 1
- return lengthrule
- def newnote(oldnote, pitchrule, lengthrule):
- #create a new note given the old note and the markov rules
- newnote = note()
- newnote.start = str(float(oldnote.start) + float(oldnote.length))
- newnote.pitch = random.choice(pitchrule[oldnote.pitch])
- newnote.length = random.choice(lengthrule[oldnote.length])
- return newnote
- def writenote(currentnote, file):
- notestring = str(currentnote.pitch)+' '+str(currentnote.start)+' '+str(currentnote.length)+'\n' #just converting everything to strings "just in case"
- file.write(notestring)
- #main program thing
- data = readdata()
- pitchrule = makepitchrule(data)
- lengthrule = makelengthrule(data)
- currentnote = note(random.choice(list(pitchrule.keys())), 0, random.choice(list(lengthrule.keys()))) #random first note
- with open('music.txt', mode='wt') as file: #was gonna open in the writing funtion but that's a bad idea
- for i in range(100):
- writenote(currentnote, file)
- currentnote = newnote(currentnote, pitchrule, lengthrule)
Advertisement
Add Comment
Please, Sign In to add comment