#!/bin/python ################################################################################ # # MarkovSamp - Joe Mariglio # #=============================================================================== # # reads in a .wav file (mono only, atm) # analyzes samples and generates a transition table using a memory depth of # and generates a markov chain of length * samps # outputs a .wav file # ################################################################################ import re, sys, string, os.path, getopt, random, math, wave, array dic = {} def parse(infile): bytes = infile.readframes(infile.getnframes()) ints = array.array('h',bytes) output = [] it = iter(ints) for i in it: output.append(i) return output def iter_flatten(iterable): it = iter(iterable) for e in it: if isinstance(e, (list, tuple)): for f in iter_flatten(e): yield f else: yield e def flatten(signal): return [i for i in iter_flatten(signal)] def analyze(array, depth): i = 0 for item in array: print int(100*(float(i) / len(array))) context = [] end = i + depth +1 if item in dic.keys(): for j in range(i+1,end): context.append(array[j%len(array)]) addContext(item, context) else: for j in range(i+1,end): context.append(array[j%len(array)]) dic[item] = [context] i = i + 1 def addContext(token, context): dic[token].append(context) def generate(depth, length): start = random.choice(dic.keys()) output = [] for i in range(0,length): value = random.choice(dic[start]) start = value[depth-1] output.append(value) print "flattening sample matrix..." output = flatten(output) return output def main(argv): if len(sys.argv) == 5: inpath = sys.argv[1] infile = wave.open(inpath, "rb") outpath = sys.argv[4] depth = int(sys.argv[2]) length = int(sys.argv[3]) lines = parse(infile) print "building transition tables for:" analyze(lines, depth) print "generating markov chain..." output = generate(depth, length) print "writing output to file..." signal = '' for i in range(len(output)): signal += wave.struct.pack('h',output[i]) outfile = wave.open(str(outpath), "wb") outfile.setnchannels(infile.getnchannels()) outfile.setsampwidth(infile.getsampwidth()) outfile.setframerate(infile.getframerate()) outfile.setnframes(length*depth) outfile.writeframes(signal) infile.close() outfile.close() #print output else: print "usage: markovSamp.py " print "where is number of samples per unit" print "and is the output length in units." if __name__ == '__main__': import re, sys, string, os.path, getopt, random, math main(sys.argv[1:])