def playMeasure(self, song_name, measure_num=0, tempo=120): measure = MIDIFile(1) track, time, channel = 0, 0, 0 measure.addTrackName(track, time, "Measure") measure.addTempo(track, time, tempo) # Add notes to measure. for note in self: pitch = note.pitch duration = note.getDuration() time = note.getTime() volume = note.getVolume() measure.addNote(track, channel, pitch, time, duration, volume) measure_num = str(measure_num) # Write the song to a file. os.system("touch .songs/" + song_name + "/measure" + measure_num + ".mid") binfile = open( ".songs/" + song_name + "/measure" + measure_num + ".mid", 'wb') measure.writeFile(binfile) binfile.close() os.system("fluidsynth -i " + felixNamespace.fluidsynthPath + " .songs/" + song_name + "/measure" + measure_num + ".mid > .dump")
def create_MIDI(self): # Create the MIDIFile Object with n track MyMIDI = MIDIFile(len(self.sequence_list), removeDuplicates = False, deinterleave = False) for i in range(len(self.sequence_list)): self.construct_seq(self.sequence_list[i].stream, i, 100, MyMIDI) self.change_instrument(MyMIDI, i, 0, 0, self.sequence_list[i].instrument) # write MIDI file to disk. binfile = open('output.mid', 'wb') MyMIDI.writeFile(binfile) binfile.close()
def playSong(self): the_song = MIDIFile(1) # Note: 1 here is the number of tracks. time = 0 # Initialize time track = 0 the_song.addTrackName(track,time,self.song_name) # Track = 0 the_song.addTempo(track,time,120) # 120 is the tempo. for measure in self.measures: for note in measure: the_song.addNote(track,note.getChannel(),note.getPitch(),time+note.getTime(),note.getDuration(),note.getVolume()) time += 4 song_file = open(".songs/" + self.song_name + "/" + self.song_name + ".mid","wb") the_song.writeFile(song_file) song_file.close() os.system("fluidsynth -i " + felixNamespace.fluidsynthPath + " .songs/" + self.song_name + "/" + self.song_name + ".mid > .dump")
def playSong(self): the_song = MIDIFile(1) # Note: 1 here is the number of tracks. time = 0 # Initialize time track = 0 the_song.addTrackName(track, time, self.song_name) # Track = 0 the_song.addTempo(track, time, 120) # 120 is the tempo. for measure in self.measures: for note in measure: the_song.addNote(track, note.getChannel(), note.getPitch(), time + note.getTime(), note.getDuration(), note.getVolume()) time += 4 song_file = open( ".songs/" + self.song_name + "/" + self.song_name + ".mid", "wb") the_song.writeFile(song_file) song_file.close() os.system("fluidsynth -i " + felixNamespace.fluidsynthPath + " .songs/" + self.song_name + "/" + self.song_name + ".mid > .dump")
def __init__(self, number_tracks=1, tempo=60, instrument=0, channel=None): """ instrument: can be an integer or a list channel: can be an integer or a list """ self.number_tracks = number_tracks self.midi_data = MIDIFile(number_tracks) for track in range(number_tracks): self.midi_data.addTrackName(track, 0, "Track {0}".format(track)) self.midi_data.addTempo(track, 0, tempo) instr = instrument[track] if isinstance(instrument, list) else instrument if channel is None: _channel = track elif isinstance(channel, list): _channel = channel[track] else: _channel = channel self.midi_data.addProgramChange(track, _channel, 0, instr)
def save_to_midi_file(self, path, tempo=60, beat_length=1.0, max_beat_divisions=8, max_indigestibility=4, beat_max_overlap=0.01, quantization_divisions=None, quantize=True, round_pitches=True, guess_tempo=False): if guess_tempo: flattened_recording = utilities.make_flat_list( [part.recording for part in self.parts_recorded] ) tempo = Playcorder.get_good_tempo_choice(flattened_recording) if quantize: beat_scheme = BeatQuantizationScheme(tempo, beat_length, max_beat_divisions, max_indigestibility) \ if quantization_divisions is None \ else BeatQuantizationScheme(tempo, beat_length, quantization_divisions=quantization_divisions) parts = [RecordingToXML.separate_into_non_overlapping_voices( RecordingToXML.quantize_recording( part.recording, [beat_scheme])[0], beat_max_overlap ) for part in self.parts_recorded] else: parts = [RecordingToXML.separate_into_non_overlapping_voices( part.recording, beat_max_overlap ) for part in self.parts_recorded] midi_file = MIDIFile(sum([len(x) for x in parts])) current_track = 0 for which_part, part in enumerate(parts): current_voice = 0 for voice in part: midi_file.addTrackName(current_track, 0, self.parts_recorded[which_part].name + " " + str(current_voice + 1)) midi_file.addTempo(current_track, 0, tempo) for pc_note in voice: assert isinstance(pc_note, MPNote) pitch_to_notate = int(round(pc_note.pitch)) if round_pitches else pc_note.pitch midi_file.addNote(current_track, 0, pitch_to_notate, pc_note.start_time, pc_note.length, int(pc_note.volume*127)) current_track += 1 current_voice += 1 bin_file = open(path, 'wb') midi_file.writeFile(bin_file) bin_file.close()
def playMeasure(self,song_name,measure_num=0,tempo=120): measure = MIDIFile(1) track, time, channel = 0, 0, 0 measure.addTrackName(track,time,"Measure") measure.addTempo(track,time, tempo) # Add notes to measure. for note in self: pitch = note.pitch duration = note.getDuration() time = note.getTime() volume = note.getVolume() measure.addNote(track,channel,pitch,time,duration,volume) measure_num = str(measure_num) # Write the song to a file. os.system("touch .songs/" + song_name + "/measure" + measure_num + ".mid") binfile = open(".songs/" + song_name + "/measure" + measure_num + ".mid", 'wb') measure.writeFile(binfile) binfile.close() os.system("fluidsynth -i " + felixNamespace.fluidsynthPath + " .songs/" + song_name + "/measure" + measure_num + ".mid > .dump")
def GenerateMidi(notes, tempo, out): song = MIDIFile(1) track = 0 time = 0 song.addTrackName(track, time, "Generated by Midi Server") song.addTempo(track, time, tempo) channel = 0 def AddNote(pitch, time, duration): song.addNote(track, channel, pitch, time, duration, 100) def SetEndTime(time): # add a no-op event to make sure we wait one beat the end, # to add time for the last note to fade song.addTempo(track, time + 1, 120) Parse(notes, AddNote, SetEndTime) song.writeFile(out)
def main(progpath, subspath): myMidifile = MIDIFile(1) track = 0 time = 0 myMidifile.addTrackName(track, time, "Programmatically Generated Sound") myMidifile.addTempo(track, time, 120) instructions_to_notes = {} subfile = open(subspath, "r") for line in subfile: print (line[:-1]).split(",") instruction, duration, opcode = (line[:-1]).split(",") instructions_to_notes[instruction] = ((int(opcode, 16) % 12)+69, int(duration)) subfile.close() # Notes is a list of (pitch, duration) pairs notes = [] progfile = open(progpath, "r") for line in progfile: tokens = line.split() if tokens: instr = tokens[0] if instr in instructions_to_notes: notes.append(instructions_to_notes[instr]) progfile.close() channel = 0 volume = 100 time = 0 for note in notes: pitch = note[0] duration = note[1] myMidifile.addNote(track, channel, pitch, time, duration, volume) time += duration binfile = open("output.mid", "wb") myMidifile.writeFile(binfile) binfile.close()
def save_to_file(filename, consolidated): midi = MIDIFile(1) track = 0 channel = 0 total_beats_so_far = 0 midi.addTempo(track, total_beats_so_far, _beats_per_minute) for c in consolidated: start = total_beats_so_far duration = _beats_per_window * c['windows'] volume = 100 pitch = find_midi_pitch_by_frequency(c['frequency']) midi.addNote(track, channel, pitch, total_beats_so_far, duration, volume) print 'add note', pitch, total_beats_so_far, duration total_beats_so_far += duration handler = open(filename, 'wb') midi.writeFile(handler) handler.close()
def save_to_file(filename, consolidated): midi = MIDIFile(1) track = 0 channel = 0 total_beats_so_far = 0 midi.addTempo(track, total_beats_so_far, _beats_per_minute) for c in consolidated: start = total_beats_so_far duration = _beats_per_window * c['windows'] volume = 100 pitch = find_midi_pitch_by_frequency(c['frequency']) midi.addNote(track, channel, pitch, total_beats_so_far, duration, volume) print 'add note', pitch, total_beats_so_far, duration total_beats_so_far+= duration handler = open(filename, 'wb') midi.writeFile(handler) handler.close()
class Midi(object): def __init__(self, number_tracks=1, tempo=60, instrument=0, channel=None): """ instrument: can be an integer or a list channel: can be an integer or a list """ self.number_tracks = number_tracks self.midi_data = MIDIFile(number_tracks) for track in range(number_tracks): self.midi_data.addTrackName(track, 0, "Track {0}".format(track)) self.midi_data.addTempo(track, 0, tempo) instr = instrument[track] if isinstance(instrument, list) else instrument if channel is None: _channel = track elif isinstance(channel, list): _channel = channel[track] else: _channel = channel self.midi_data.addProgramChange(track, _channel, 0, instr) def seq_chords(self, seqlist, track=0, time=0, channel=None): if track + 1 > self.number_tracks: raise MidiError("You are trying to use more tracks than we have.") _channel = channel if channel is not None else track for item in seqlist: if isinstance(item, NoteSeq): volume = item[0].volume dur = item[0].midi_dur for note in item: self.midi_data.addNote(track, _channel, note.midi_number, time, dur, volume) time += dur elif isinstance(item, Rest): time += item.midi_dur else: raise MidiError("The input should be a list of NoteSeq but yours is a {0}: {1}".format(type(seqlist), seqlist)) return time def seq_notes(self, noteseq, track=0, time=0, channel=None): if track + 1 > self.number_tracks: raise MidiError("You are trying to use more tracks than we have.") _channel = channel if channel is not None else track for note in noteseq: if isinstance(note, Note): self.midi_data.addNote(track, _channel, note.midi_number, time, note.midi_dur, note.volume) else: # we ignore the rests pass time += note.midi_dur return time def write(self, filename): if isinstance(filename, str): with open(filename, 'wb') as midifile: self.midi_data.writeFile(midifile) else: self.midi_data.writeFile(filename)
def ptcop2midi(ptcop, outfile): midi = MIDIFile(200) for i, unit in enumerate(ptcop.units): channel = 0 track = i midi.addTrackName(i, channel, unit.name) midi.addTempo(i, channel, int(sys.argv[2])) note = 80 velocity = 104 porta = 0 bend = 0x4000/2 for e in unit.events: beat = ptcop2midi_beat(e.position) if e.type == pxtone.EventType.VOICE: track = e.value # pass elif e.type == pxtone.EventType.ON: midi.addNote(track, channel, note, beat + PADDING, ptcop2midi_beat(e.value) - PADDING, velocity) elif e.type == pxtone.EventType.VELOCITY: velocity = e.value elif e.type == pxtone.EventType.NOTE: note = ptcop2midi_note(e.value) on = unit.on(e.position) if on: if on.position == e.position: # reset pitch bend if bend != 0x4000/2: bend = 0x4000/2 midi.addPitchBendEvent(track, channel, ptcop2midi_beat(on.position) + PADDING, bend); pass else: # glissando # on what note did the "on" begin? old_note = unit.note_before(e.position) old_note = ptcop2midi_note(old_note) # semitones to travel diff = note - old_note if diff > PITCH_BEND_SEMITONES: diff = PITCH_BEND_SEMITONES elif diff < -PITCH_BEND_SEMITONES: diff = -PITCH_BEND_SEMITONES # where the pitch bend should wind up target = 0x4000/2 + diff * 0x4000 / (PITCH_BEND_SEMITONES*2) # print porta, target startbeat = beat if startbeat == midi2ptcop_beat(on.position): startbeat += PADDING endbeat = beat + ptcop2midi_beat(porta) end = midi2ptcop_beat(on.position + on.value) if endbeat >= end: shortened = end - PADDING target = map(shortened, startbeat, endbeat, bend, target) endbeat = shortened # if endbeat >= beat: midi.addPitchBendEvent(track, channel, startbeat, bend); midi.addPitchBendEvent(track, channel, endbeat, target); bend = target elif e.type == pxtone.EventType.KEY_PORTA: porta = 0 #e.value # elif e.type == pxtone.EventType.VOLUME: # midi.addControllerEvent(track, # channel, # beat, # MIDIEvents.VOLUME, # e.value) # elif e.type == pxtone.EventType.PAN: # midi.addControllerEvent(track, # channel, # beat, # MIDIEvents.PAN, # e.value) out = open(outfile, 'wb') midi.writeFile(out) out.close()
overrides = {} showProgress = False midiVelocity = 64 for override in sys.argv[1:-2]: p = override.split(":") if (p[0] == "showprogress"): showProgress = True elif (p[0] == "midivelocity"): midiVelocity = int(p[1]) else: overrides[p[0]] = p[1] if (showProgress): NamedWindow("Main") ResizeWindow("Main", 640, 480) cap = CaptureFromFile(sys.argv[len(sys.argv)-1]) scanner = KeyboardScanner(QueryFrame(cap), overrides) midi = MIDIFile(1) midi.addTrackName(0,0,"Transcribed from Synthesia") midi.addTempo(0,0,120.0) noteDeltas = {} while True: t = GetCaptureProperty(cap, CV_CAP_PROP_POS_MSEC) / 500.0 print t, "\r", frame = QueryFrame(cap) if (frame == None): break changes = scanner.scanFrame(frame) if (showProgress): ShowImage("Main", scanner.debugImage) WaitKey(1) for pitch in changes:
def ptcop2midi(ptcop, outfile): midi = MIDIFile(200) print ptcop2midi_beat(8160) for i, unit in enumerate(ptcop.units): channel = 0 track = i midi.addTrackName(i, channel, unit.name) midi.addTempo(i, channel, int(sys.argv[2])) note = 80 velocity = 104 porta = 0 bend = 0x4000 / 2 for e in unit.events: beat = ptcop2midi_beat(e.position) if e.type == pxtone.EventType.VOICE: # track = e.value velocity = e.value elif e.type == pxtone.EventType.ON: # find all note events in the range of # (beat, ptcop2midi_beat(e.value)) notes = unit.notes_between(e.position, e.position + e.value) if not notes: midi.addNote(track, channel, note, beat, max(ptcop2midi_beat(e.value) - 0.001, 0.001), velocity) else: if notes[0].position != e.position: midi.addNote( track, channel, note, beat, ptcop2midi_beat(notes[0].position - e.position), velocity) j = 0 l = len(notes) - 1 while j < l: midi.addNote( track, channel, ptcop2midi_note(notes[j].value), ptcop2midi_beat(notes[j].position), ptcop2midi_beat(notes[j + 1].position - notes[j].position), velocity) j += 1 midi.addNote( track, channel, ptcop2midi_note(notes[-1].value), ptcop2midi_beat(notes[-1].position), max( ptcop2midi_beat(e.position + e.value - notes[-1].position) - 0.001, 0.001), velocity) elif e.type == pxtone.EventType.VELOCITY: # velocity = e.value pass elif e.type == pxtone.EventType.NOTE: note = ptcop2midi_note(e.value) elif e.type == pxtone.EventType.KEY_PORTA: midi.addPitchBendEvent(track, channel, beat, e.value) # elif e.type == pxtone.EventType.VOLUME: # midi.addControllerEvent(track, # channel, # beat, # MIDIEvents.VOLUME, # e.value) # elif e.type == pxtone.EventType.PAN: # midi.addControllerEvent(track, # channel, # beat, # MIDIEvents.PAN, # e.value) out = open(outfile, 'wb') midi.writeFile(out) out.close()
def ptcop2midi(ptcop, outfile): midi = MIDIFile(len(ptcop.units)) for i, unit in enumerate(ptcop.units): channel = 0 midi.addTrackName(i, channel, unit.name) midi.addTempo(i, channel, ptcop.tempo) note = 80 velocity = 104 porta = 0 bend = 0x4000 / 2 for e in unit.events: beat = ptcop2midi_beat(e.position) if e.type == pxtone.EventType.ON: midi.addNote(i, channel, note, beat, ptcop2midi_beat(e.value), velocity) elif e.type == pxtone.EventType.VELOCITY: velocity = e.value elif e.type == pxtone.EventType.NOTE: note = ptcop2midi_note(e.value) on = unit.on(e.position) if on: if on.position == e.position: # reset pitch bend if bend != 0x4000 / 2: bend = 0x4000 / 2 midi.addPitchBendEvent(i, channel, beat, bend) else: # glissando # on what note did the "on" begin? old_note = unit.note_before(e.position) old_note = ptcop2midi_note(old_note) # semitones to travel diff = note - old_note # where the pitch bend should wind up target = 0x4000 / 2 + diff * 0x4000 / ( PITCH_BEND_SEMITONES * 2) print porta, target midi.addPitchBendEvent(i, channel, beat, bend) midi.addPitchBendEvent(i, channel, beat + ptcop2midi_beat(porta), target) bend = target elif e.type == pxtone.EventType.KEY_PORTA: porta = e.value # elif e.type == pxtone.EventType.VOLUME: # midi.addControllerEvent(i, # channel, # beat, # MIDIEvents.VOLUME, # e.value) # elif e.type == pxtone.EventType.PAN: # midi.addControllerEvent(i, # channel, # beat, # MIDIEvents.PAN, # e.value) out = open(outfile, 'wb') midi.writeFile(out) out.close()
''' Created by: Brian Richard, Jonathan Zhang, Aneel Yelamanchili on July 28 2014 [email protected], [email protected], [email protected] ''' from MidiFile import MIDIFile import song_maker, GUI #builds a midi, melody, and three harmonies midi1 = MIDIFile(1) mel1 = song_maker.Melody(4) harm = song_maker.Harmony(mel1) mel1.buildNotes() harm.buildNotes() harm.buildNotes() harm.buildNotes() mel1.buildMelody(midi1) harm.buildHarmony(midi1) #writes to MIDI file with open('output.mid', 'wb') as my_file: midi1.writeFile(my_file) melDuration = [] melNotes = [] harmDuration = [] harm1Notes = [] harm2Notes = []
def midiExport(liveSet, midiFilePath, separateChannels=False): print('Init Midi Export') # How Many Midi Tracks in liveSet? usedMidiTrack = 0 for track in liveSet.tracks: if len(track.notes) != 0: usedMidiTrack += 1 #print ("Used Midi Track count:", usedMidiTrack) # Create the MIDIFile Object with 1 track MyMIDI = MIDIFile(len(liveSet.tracks), file_format=1, adjust_origin=True) i = 0 for track in liveSet.tracks: # Tracks are numbered from zero. Times are measured in beats. if track.midiExport: #len(track.notes) != 0 and trackId = i channel = i % 16 if separateChannels else 0 time = 0 # Add track name. name = str(track.name) MyMIDI.addTrackName(trackId, time, name) # Add tempo Map to first track. if trackId == 0: events = getAutomationEvents(liveSet.tempoMap) for event in events: MyMIDI.addTempo(trackId, event['Time'], event['Value']) # Add Notes. for note in track.notes: pitch = note.pitch time = note.start duration = note.duration volume = note.velocity MyMIDI.addNote(trackId, channel, pitch, time, duration, volume) # Add Clip Automations to MidiTrack for clip in track.arrangementClips: for envelope in clip.envelopes: events = getAutomationEvents(envelope.events) target = envelope.targetName for event in events: time = event['Time'] + clip.startTime - clip.loopStart value = int(event['Value']) #print('time:{}, value:{}'.format(time, value)) if target == 'Pitch Bend': MyMIDI.addPitchWheelEvent(trackId, channel, time, value) print(time, value) elif target == 'Channel Pressure': MyMIDI.addChannelPressureEvent( trackId, channel, time, value) # Prevent CC7(Volume) and CC10(Pan) Conflicts elif int(target) != 7 and int(target) != 10: MyMIDI.addControllerEvent(trackId, channel, time, int(target), value) if isinstance(target, int) and int( target) == 7 and not track.volumeMidiExport: MyMIDI.addControllerEvent(trackId, channel, time, int(target), value) if isinstance(target, int) and int( target) == 10 and not track.panMidiExport: MyMIDI.addControllerEvent(trackId, channel, time, int(target), value) i += 1 # Add Volume Automation to Track if track.volumeMidiExport: events = getAutomationEvents(track.volumeAutomationEvents) for event in events: time = event['Time'] value = event['Value'] # Scale value [0, 1] to [0, 100] and [1, 2] and [100, 127] if value <= 1: value = int(value * 100) else: value = int(100 + value * 28 / 2) #print('time:', time, 'value:', value) MyMIDI.addControllerEvent(trackId, channel, time, 7, value) # Add Pan Automation to Track if track.panMidiExport: events = getAutomationEvents(track.panAutomationEvents) for event in events: time = event['Time'] value = event['Value'] # Scale value [-1, 1] to [0, 127] value = int((value + 1) * 64) MyMIDI.addControllerEvent(trackId, channel, time, 10, value) # And write it to disk. binfile = open(midiFilePath, 'wb') MyMIDI.writeFile(binfile) binfile.close() print('Midi Export Done')
def ptcop2midi(ptcop, outfile): midi = MIDIFile(200) print ptcop2midi_beat(8160) for i, unit in enumerate(ptcop.units): channel = 0 track = i midi.addTrackName(i, channel, unit.name) midi.addTempo(i, channel, int(sys.argv[2])) note = 80 velocity = 104 porta = 0 bend = 0x4000/2 for e in unit.events: beat = ptcop2midi_beat(e.position) if e.type == pxtone.EventType.VOICE: # track = e.value velocity = e.value elif e.type == pxtone.EventType.ON: # find all note events in the range of # (beat, ptcop2midi_beat(e.value)) notes = unit.notes_between(e.position, e.position + e.value) if not notes: midi.addNote(track, channel, note, beat, max(ptcop2midi_beat(e.value)-0.001, 0.001), velocity) else: if notes[0].position != e.position: midi.addNote(track, channel, note, beat, ptcop2midi_beat(notes[0].position - e.position), velocity) j = 0; l = len(notes)-1 while j < l: midi.addNote(track, channel, ptcop2midi_note(notes[j].value), ptcop2midi_beat(notes[j].position), ptcop2midi_beat(notes[j+1].position - notes[j].position), velocity) j += 1 midi.addNote(track, channel, ptcop2midi_note(notes[-1].value), ptcop2midi_beat(notes[-1].position), max(ptcop2midi_beat(e.position + e.value - notes[-1].position)-0.001, 0.001), velocity) elif e.type == pxtone.EventType.VELOCITY: # velocity = e.value pass elif e.type == pxtone.EventType.NOTE: note = ptcop2midi_note(e.value) elif e.type == pxtone.EventType.KEY_PORTA: midi.addPitchBendEvent(track, channel, beat, e.value); # elif e.type == pxtone.EventType.VOLUME: # midi.addControllerEvent(track, # channel, # beat, # MIDIEvents.VOLUME, # e.value) # elif e.type == pxtone.EventType.PAN: # midi.addControllerEvent(track, # channel, # beat, # MIDIEvents.PAN, # e.value) out = open(outfile, 'wb') midi.writeFile(out) out.close()
def save_file(music_file, notes): # Create the MIDIFile Object MyMIDI = MIDIFile(1) #offsets = [4,1,0,0,0,2,0] offsets = [0,0,0,2,0,1,3,0] # Add track name and tempo. The first argument to addTrackName and # addTempo is the time to write the event. track = 0 time = 0 MyMIDI.addTrackName(track,time,"Sample Track") MyMIDI.addTempo(track,time, 90) channel = 0 duration = 0.25 volume = 80 time+=1 new_time = time for note in notes: last_time = new_time random.shuffle(offsets) offset = offsets[0] new_time = time - (duration * offset) new_duration = duration * (1 + offset) if new_time < last_time: new_time = last_time new_duration = time + 1 - new_time pitch = 60 + note print new_time, new_duration, pitch MyMIDI.addNote(track,channel,pitch,(new_time + 0.05*(random.random()-0.5)),new_duration,volume + int(20*random.random())) time += duration print 'time is now: ', time print 'duration is now: ', duration MyMIDI.addNote(track,channel,55,time,2,0) binfile = open(music_file, 'wb') MyMIDI.writeFile(binfile) binfile.close()