User:Danny van der Kleij/Markov Piano

From XPUB & Lens-Based wiki

[[Category: Markov Chant]

Unsure if this is totally right, but it works.

import os, random
samplelist = ['Piano_A', 'Piano_B', 'Piano_C', 'Piano_D', 'Piano_E', 'Piano_F', 'Piano_G', 'Piano_F', 'Piano_E', 'Piano_D', 'Piano_C', 'Piano_B', 'Piano_A', 'end']


#need to know, which sample comes after another sample. for example after Piano_B can come Piano_A or Piano_C.
dictionary = {}

# i is what counts through the list with numbers(0-12) r = the corresponding elements in the list, so we get
# i = 2, r = 'piano_C'
for (i, r) in enumerate(samplelist):
  if i < len(samplelist) - 1:
    if samplelist[i] not in dictionary:
      dictionary[r] = []
    dictionary[r].append(samplelist[i+1])

#now walk through the dictionary each time chosing a new element 
#from the list of choices and storing that in a new list.

for j in range(0, 1):
  markovlist = ['Piano_A']
  start = random.choice(dictionary['Piano_A'])
  while start != 'end':
    markovlist.append(start)
    start = random.choice(dictionary[start])

print markovlist
# now after having the new markov chain list we play it using mplayer and system calls.
for (k, s) in enumerate(markovlist):
  cmd = 'mplayer %s.wav' % (markovlist[k])  
  os.system(cmd)