#!/usr/bin/python import os,termios,time,math,random,sys from string import * from midi_functions import * #port=open('/dev/ttyS0','r') events=[] event_times=[] outfilename=sys.argv[1] def input_song(): global events, event_times ######## midi = os.open('/dev/ttyS0',0) old = termios.tcgetattr(midi) new = termios.tcgetattr(midi) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 termios.tcsetattr(midi, termios.TCSANOW, new) ###### put midi data here for now: try: while 1: c = os.read(midi, 1) if c != '\xfe': if c >= '\x80': event_times.append(time.time()) events.append(c) finally: termios.tcsetattr(midi, termios.TCSAFLUSH, old) def reorder_times(): global event_times delta_times=[chr(0x00)] for x in range(1,len(event_times),1): new=write_var_length(int(round((event_times[x]-event_times[x-1])*1000))) delta_times.append(new) return delta_times def make_track_data(): global events delta_times=reorder_times() track_out_array=[] track_len_chars='' count=0 ##### add Tempo of 1,000,000: track_out_array.append('%c%c%c%c%c%c%c' % (0x0,0xff,0x51,0x03,0x0f,0x42,0x40)) for event in events: if event >= '\x80': track_out_array.append(delta_times[count]) count+=1 track_out_array.append(event) track_out_array.append('%c%c%c%c' % (0x0,0xff,0x2f,0x0)) track_out_string=join(track_out_array,'') track_length=len(track_out_string) for z in range(3,-1,-1): track_len_chars=track_len_chars + chr((track_length & (0xff<<(z*8)))>>(z*8)) return track_out_string, track_len_chars def midi_file_dump(name): outfile=open(name,'w') track,length=make_track_data() outfile.write('MThd') ### header outfile.write('%c%c%c%c%c%c%c%c%c%c'% (0x0,0x0,0x0,0x06,0x0,0x0,0x0,0x01,0x03,0xe8)) outfile.write('MTrk') ### track outfile.write('%s' % length) outfile.write('%s' % track) outfile.close() print "MIDI file written." print print "entering record mode...interrupt with ^C to stop" try: input_song() except: midi_file_dump(outfilename)