def output_to_midi(OUTPUT_PATH, PRED_MIDI_PATH): predmidi = pd.read_csv(PRED_MIDI_PATH) print(predmidi.shape) mf = MIDIFile(1) # only 1 track track = 0 # the only track time = 0 # start at the beginning mf.addTrackName(track, time, "Sample Track") mf.addTempo(track, time, 120) # add some notes channel = 0 volume = 100 duration = 1 for i in range(int(predmidi.shape[0])): for j in range(int(predmidi.shape[1])): x = predmidi.iloc[i, j] if (x == 1): pitch = j time = i mf.addNote(track, channel, pitch, time, duration, volume) # write it to disk with open(OUTPUT_PATH, 'wb') as outf: mf.writeFile(outf) return 0
def __play(arg_time, tone: str, octave: str): # CREATE MEMORY FILE memFile = BytesIO() MyMIDI = MIDIFile(1, adjust_origin=True) track = 0 time = 0 channel = 0 pitch = int(__get_tones(tone, octave)) duration = arg_time volume = 100 MyMIDI.addProgramChange(track, channel, time, 90) MyMIDI.addTempo(track, time, 60) # WRITE A SCALE MyMIDI.addNote(track, channel, pitch, time, duration + 1, volume) MyMIDI.writeFile(memFile) # PLAYBACK clock = Clock() # memFile.seek(0) # THIS IS CRITICAL, OTHERWISE YOU GET THAT ERROR! temp = BytesIO(memFile.getvalue()) pygame.mixer.music.load(temp) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): clock.tick(1)
def write_midi(note_vals, total_dist, total_time, musicfile): """ TO BE DEPRECATED """ # create your MIDI object mf = MIDIFile( 1, adjust_origin=True) # only 1 track, changed adjust_origin to T track = 0 # the only track time = 0 # start at the beginning time_factor = total_time / total_dist mf.addTrackName(track, time, "Sample Track") mf.addTempo(track, time, (1 / time_factor)) channel = 0 note_conversion = {0: 60, 1: 62, 2: 64, 3: 67, 4: 69} for i in note_vals: # add some notes pitch = note_conversion[i[1]] time = i[0][0] * time_factor duration = 4 # can be parameterized volume = 100 # can be parameterized mf.addNote(track, channel, pitch, time, duration, volume) ''' http://stackoverflow.com/questions/11059801/how-can-i-write-a-midi-file-with-python how to write a note (each pitch # is a piano key) pitch = 60 # C4 (middle C) time = 0 # start on beat 0 duration = 1 # 1 beat long mf.addNote(track, channel, pitch, time, duration, volume) ''' # write it to disk with open(musicfile, 'wb') as outf: mf.writeFile(outf)
def create_midi(pitch): """ Creates a midi file of just one note repeated 32 times :param pitch: pitch of note :type pitch: int :returns: None :rtype: None """ MyMIDI = MIDIFile(1) track = 0 time = 0 # creates a template for a midi track MyMIDI.addTrackName(track,time, str(pitch)) MyMIDI.addTempo(track,time,120) channel = 0 volume = 120 # pitch = 60 duration = 1 for i in range(3200): MyMIDI.addNote(track,channel,pitch,time,duration,volume) time += duration # write midi file file_name = str(pitch) + '.mid' binfile = open(file_name, 'wb') MyMIDI.writeFile(binfile) binfile.close() return
def generateSong(self): print("Generating music ...") print("Final Tracks : " + str(self.tracks)) print("Final Channels : " + str(self.channels)) print("Final midi Instruments : " + str(self.track_instruments)) time = 0 self.MyMIDI = MIDIFile(len(self.tracks)) for i in range(len(self.tracks)): track_voices = self.tracks[i] channel_voices = self.channels[i] volume = 100 # 0-127, as per the MIDI standard self.MyMIDI.addTempo(track_voices, 0, self.BPM) notes = self.track_notes[i] self.MyMIDI.addProgramChange(track_voices, channel_voices, 0, self.track_instruments[i]) for (i, info) in enumerate(notes): if info[1] != 0: self.MyMIDI.addNote( track_voices, channel_voices, info[0], utils.convertTicks2Beat(info[3], self.ticks_per_beat), utils.convertTicks2Beat(info[1], self.ticks_per_beat), volume) with open(constants.PATH_GENERATED_SONG, "wb") as output_file: self.MyMIDI.writeFile(output_file) print("generateSong done") return constants.PATH_GENERATED_SONG
def export(self, filename): 'Exports the project to a MIDI-file' # entries must contain stuff if len(self.entries) == 0: return # reset the midi variable global Midi Midi = MIDIFile(1) Midi.addTrackName(track, time_start, 'MIDI Cuer') # the great export loop all_beats = int( math.ceil( self.entries[len(self.entries)-1][3] ) ) out = {} for x in xrange(1, len(self.entries)): out.update( self.calcIterBeats( self.entries[x-1][3], self.entries[x][3], self.entries[x-1][2], self.entries[x][2], self.stepsize ) ) for x in sorted(out.iterkeys()): AddTempo(x, out[x]) if self.BeatExists(x): AddNote(x) # de-comment following 3 lines for debugging during output # print 'Debuggin:' # for x in sorted(out): # print x, out[x] SaveIt(filename)
def matrix_to_midi(notes, filename='matrix.mid', tempo=60): """ Simplify midi generation note format: PITCH|START|DURATION|VOLUME """ # Midi file with one track mf = MIDIFile(1) track = 0 time = 0 mf.addTrackName(track, time, filename[7:-4]) # Default # FIXME tempo -- time relation is not well defined mf.addTempo(track, time, tempo) channel = 0 time_per_tick = 2**-5 for note in notes: pitch = note[0] start = note[1] * time_per_tick stop = note[2] * time_per_tick vol = note[3] mf.addNote(track, channel, pitch, start, stop, vol) # Save as file with open(filename, 'wb') as fout: mf.writeFile(fout)
def write_midi_file(song, file_name): """ Escriba una frase musical en un archivo MIDI en el mismo directorio. Utiliza MIDIUtil. : param song: la frase musical para escribir en un archivo : param file_name: el nombre del archivo MIDI """ # Crea el objeto MIDIFile con # pista my_midi = MIDIFile(12) # Las pistas están numeradas desde cero. Los tiempos se miden en latidos. beats. track = 4 time = 4 # Agrega el nombre y el tempo de la pista. my_midi.addTrackName(track, time, "Principal") my_midi.addTempo(track, time, MIDI_TEMPO) # Agrega una nota. addNote espera la siguiente información: track = 8 # (constante) channel = 2 # (constante) volume = 100 # (constante) # Ahora agrega las notas for beat in song: pitch, time, duration = beat my_midi.addNote(track, channel, pitch, time, duration, volume) # Y escribe en el disco. bin_file = open(file_name, 'wb') my_midi.writeFile(bin_file) bin_file.close()
def initializeMidi(self): self.midi = MIDIFile(len(self.tracks)) for i, track in enumerate(self.tracks): self.midi.addTrackName(i, 0, track['Name']) self.midi.addTempo(i, 0, self.bpm) self.midi.addProgramChange(i, 0, 0, track['Program'])
def render(self, doc, output_file='output.mid'): ''' Produces actual output. Assumptions: separate channel for each DataObject''' # Note - I fixed a bug in MidiFile.py that was causing crashes (part of the midiutil lib). # Author confirms this is a bug, and will eventually fix and patch, but for now there's a # modified version of midiutil bundled with the project. # Create the MIDIFile Object with 1 track MyMIDI = MIDIFile(1) # Tracks are numbered from zero. Times are measured in beats. track = 0 time = 0 # Add track name and tempo. MyMIDI.addTrackName(track, time, "Sample Track") MyMIDI.addTempo(track, time, self.tempo) for channel, do in enumerate(doc): for cc_number, time_series in do.items(): for i, val in enumerate(time_series): time = float(i) / time_series.sample_rate logging.debug(str(time) + ' ' + str(val)) MyMIDI.addControllerEvent(track, channel, time, cc_number, int(val)) # And write it to disk. with open(output_file, 'wb') as binfile: MyMIDI.writeFile(binfile) return MyMIDI
def __init__(self, track_configs): self.midi_file = MIDIFile(len(track_configs)) self.track_time = [] for i, config in enumerate(track_configs): self.track_time.append(0) self.midi_file.addTrackName(i, config.time, config.name) self.midi_file.addTempo(i, config.time, config.tempo)
def generateMidiFile(songNoteLst, MCType): print("Generating Song File") newSong = MIDIFile(1) # Tracks are numbered from zero. Times are measured in beats. track = 0 time = 0 # Add track name and tempo. newSong.addTrackName(track, time, "Song Generated Using Markov Chain") newSong.addTempo(track, time, 360) channel = 0 for note in songNoteLst: if note != -1: # Add a note. addNote expects the following information: pitch = note duration = random.randint(1,4) volume = 255 # Now add the note. newSong.addNote(track,channel,pitch,time,duration,volume) time += duration # And write it to disk. write_file_name = "output_" + MCType + "_MC.midi" binfile = open(write_file_name, 'wb') newSong.writeFile(binfile) binfile.close() print("Finished")
def toMidi(the_input, fname): MyMIDI = MIDIFile(1) track = 0 time = 0 channel = 0 tickTime = .25 MyMIDI.addTrackName(track, time, "Sample Track") MyMIDI.addTempo(track, time, 480) the_input = the_input.transpose() flag = np.zeros((127, )) startNote = np.zeros((127, )) myTick = 0 for xMan in range(len(the_input)): myTick += tickTime for yMan in range(len(the_input[xMan])): if the_input[xMan][yMan] > 0: if flag[yMan - 1] == 0: startNote[yMan - 1] = myTick flag[yMan - 1] += tickTime else: if flag[yMan - 1] != 0: pitch = yMan time = startNote[yMan - 1] duration = flag[yMan - 1] volume = 100 MyMIDI.addNote(track, channel, pitch, time, duration, volume) print("appending: " + str(yMan) + " at " + str(time) + " for " + str(duration)) flag[yMan - 1] = 0 binfile = open(fname, 'wb') MyMIDI.writeFile(binfile) binfile.close()
def writePiece(piece, title='Genetic Algos', filename='./pieces/untitled.mid', bpm=120, debug=False): mf = MIDIFile(1) track = 0 time = 0 mf.addTrackName(track, time, title) mf.addTempo(track, time, bpm) # add some notes channel = 0 volume = 100 for measure in piece: for note in measure: if note.midi_note is not None: mf.addNote(track, channel, note.midi_note, time, note.duration, volume) time += note.duration with open(filename, 'wb') as outf: mf.writeFile(outf) if debug: print("Writing to", fname)
def generate_midi(self, output_path: str, track_name: str = 'Sample'): mf = MIDIFile(1) # only 1 track track = 0 # the only track time_step = 0 # start at the beginning # create your MIDI object # add some notes channel = 0 volume = 100 mf.addTrackName(track, time_step, track_name) mf.addTempo(track, time_step, 120) for pcgts in self.pcgts: page = pcgts.page music_blocks = page.music_blocks() for mb in music_blocks: for line in mb.lines: symbols = line.symbols for symbol in symbols: if symbol.symbol_type == symbol.symbol_type.NOTE: duration = 0.5 # 1 1 beat long. Calculate duration based on position in image? mf.addNote(track, channel, pitch_midi_table[Pitch(symbol.note_name.value, symbol.octave)], time_step, duration, volume) time_step = time_step + duration # write it to disk with open(output_path, 'wb') as outf: mf.writeFile(outf)
def save_midi(outfile, notes, tempo): track = 0 time = 0 midifile = MIDIFile(1) # Add track name and tempo. midifile.addTrackName(track, time, "MIDI TRACK") midifile.addTempo(track, time, tempo) channel = 0 volume = 100 for note in notes: onset = note[0] * (tempo/60.) duration = note[1] * (tempo/60.) # duration = 1 pitch = note[2] pitch = pitch.__int__() midifile.addNote(track, channel, pitch, onset, duration, volume) # And write it to disk. binfile = open(outfile, 'wb') midifile.writeFile(binfile) binfile.close()
def write_midi_file(song, file_name): """ Write a musical phrase to a MIDI file in the same directory. Uses MIDIUtil. :param song: the musical phrase to write to a file :param file_name: the name of the MIDI file """ # Create the MIDIFile Object with 1 track my_midi = MIDIFile(1) # Tracks are numbered from zero. Times are measured in beats. track = 0 time = 0 # Add track name and tempo. my_midi.addTrackName(track, time, "Main") my_midi.addTempo(track, time, MIDI_TEMPO) # Add a note. addNote expects the following information: track = 0 # (constant) channel = 0 # (constant) volume = 100 # (constant) # Now add the notes for beat in song: pitch, time, duration = beat my_midi.addNote(track, channel, pitch, time, duration, volume) # And write it to disk. if not os.path.exists('./currentRun'): os.mkdir('./currentRun') bin_file = open(file_name, 'wb') my_midi.writeFile(bin_file) bin_file.close()
class MidiFileOut: """ Write events to a MIDI file. Requires the MIDIUtil package: https://code.google.com/p/midiutil/ """ def __init__(self, numtracks = 16): from midiutil.MidiFile import MIDIFile self.score = MIDIFile(numtracks) self.track = 0 self.channel = 0 self.volume = 64 self.time = 0 def tick(self, ticklen): self.time += ticklen def noteOn(self, note = 60, velocity = 64, channel = 0, duration = 1): #------------------------------------------------------------------------ # avoid rounding errors #------------------------------------------------------------------------ time = round(self.time, 5) self.score.addNote(channel, channel, note, time, duration, velocity) def noteOff(self, note = 60, channel = 0): pass def writeFile(self, filename = "score.mid"): fd = open(filename, 'wb') self.score.writeFile(fd) fd.close()
def generate_midi(self): MyMIDI = MIDIFile(1) s = len(self.prob_matrix) track = 0 time = 0 volume = 110 channel = 0 program = self.get_instrument(self.instrument) pitch = numpy.random.randint(0, s, 1)[0] MyMIDI.addTempo(track, time, self.bpm) MyMIDI.addProgramChange(track, channel, time, program) for i in range (0,int(self.length*self.bpm)): pitch = (numpy.random.choice(s, 1, False, self.prob_matrix[pitch % s])[0]) if self.rand: pitch += (12 * numpy.random.randint(0, 2, 1)[0]) + numpy.random.randint(2*s, 5*s, 1)[0] pitch = pitch % 128 duration = numpy.random.randint(50, 400, 1)[0] / 200 MyMIDI.addNote(track, channel, pitch, time, duration, volume) time += duration os.makedirs(os.path.dirname(self.path), exist_ok=True) with open(self.path, "wb") as f: MyMIDI.writeFile(f) f.close()
def write_midi(chord_sequence, filename): # create your MIDI object mf = MIDIFile(1) # only 1 track track = 0 # the only track time = 0 # start at the beginning duration = 1 # chords will be 1 beat long mf.addTrackName(track, time, "Sample Track") mf.addTempo(track, time, 60) # add some notes channel = 0 volume = 100 for chord in chord_sequence: # Change chords to notes (list of tuples?) -> def chord_to_notes(chord) notes = chord_to_notes(chord) for note in notes: pitch = note_to_pitch(note) mf.addNote(track, channel, pitch, time, duration, volume) # Write pitches to midi file: # https://midiutil.readthedocs.io/en/latest/ # https://stackoverflow.com/questions/11059801/how-can-i-write-a-midi-file-with-python time += 2 # write it to disk with open(filename + ".mid", 'wb') as outf: mf.writeFile(outf)
def __init__(self, numtracks=1): from midiutil.MidiFile import MIDIFile self.score = MIDIFile(numtracks) self.track = 0 self.channel = 0 self.volume = 64
def midisaver(): print("s = Save n = New Sequence q = Quit") while True: choice = input("> ") if choice == 's': oldvoices = list(voices) mf = MIDIFile(4) time = 0 tracklist = [0, 1, 1, 1, 1, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2] tracknames = ['Bass', 'Drums', 'Keys', 'Lead'] for i in range(len(oldvoices)): track = tracklist[i] mf.addTrackName(track, 0, tracknames[track]) mf.addTempo(track, 0, bpm) channel = 0 for x in range(len(oldvoices[i])): if oldvoices[i][x][1] != 0: pitch = oldvoices[i][x][1] volume = oldvoices[i][x][2] time = oldvoices[i][x][0]/4 #convert from beats to sixteenths if time+1 > 8: duration = oldvoices[i][x][3] else: duration = random.choice([0.20, 0.40, 0.60, 0.80, 1]) mf.addNote(track, channel, pitch, time, duration, volume) filename = (input('Save As:') + ".mid") with open(filename, 'wb') as outf: mf.writeFile(outf) if choice == 'q': thread.interrupt_main() sys.exit() if choice == 'n': measureCount = 1 compose()
def note_sequence_to_midi_file(note_sequence, tempo, length, output_path="output"): track = 0 channel = 0 time = 0 # In beats duration = 0.5 # In beats volume = 100 tempo = int(tempo) length = int(length) MyMIDI = MIDIFile(1) MyMIDI.addTempo(track, time, tempo) note_sequence = eval(note_sequence) # Get last note step last_note_step = -1 for note in note_sequence: if note['quantized_start_step'] > last_note_step: last_note_step = note['quantized_start_step'] last_note_duration = length - last_note_step for note in note_sequence: pitch = note['pitch'] time_step = note['quantized_start_step'] if time_step == last_note_step: MyMIDI.addNote(track, channel, pitch, time_step, last_note_duration, volume) else: MyMIDI.addNote(track, channel, pitch, time_step, duration, volume) midi_date_file = str(datetime.datetime.now()).replace(" ", "_") + ".mid" midi_file_path = os.path.join(output_path, midi_date_file) with open(midi_file_path, "wb") as output_file: MyMIDI.writeFile(output_file) return midi_file_path
class FileOutput(Output): url_example = "file://foo.mid" def __init__(self, url): Output.__init__(self) outfile = url.netloc + url.path if not outfile: print "file:// output needs a filename" raise ValueError("File output needs a filename") log.info("Opening File output: %s", outfile) self.midi = MIDIFile(1) self.midi.addTrackName(0, 0, "Mic2Mid Track 0") self.midi.addTempo(0, 0, 60) self.midi.addProgramChange(0, 0, 0, 27) self.start = time.time() self.filename = outfile def close(self): Output.close(self) log.info("Closing File output: %s", self.filename) fp = open(self.filename, "wb") self.midi.writeFile(fp) fp.close() def note_on(self, note): self.midi.addNote(0, 0, self.note_to_midi(note), time.time() - self.start, 1, 100)
def makeMidi(fileName, toneLibrary, tones): """ Makes the midi file for a given set of tones """ # Create midi file tempMIDI = MIDIFile(1) track = 0 channel = 0 time = 0 # In beats tempo = 60 # In BPM volume = 100 # 0-127, as per the MIDI standard # Create the trackname and temp tempMIDI.addTrackName(track, time, fileName) tempMIDI.addTempo(track, time, tempo) # Add each tone from the current image for index, tone in enumerate(tones): # Set duration duration = .5 # Set interval between tones toneInterval = (index) * duration # Add note to track tempMIDI.addNote(track, channel, tone, time + toneInterval, duration, volume) # Write the midi track to a file with open("midiFiles/{}.mid".format(fileName), "wb") as midiFile: tempMIDI.writeFile(midiFile)
def main(argv): if len(argv) == 1: for line in open(argv[0],'r'): MyMIDI = MIDIFile(1) MyMIDI.addTempo(0,0,120) array = line.split(";") MyMIDI = makeProgression(noteToPitch(array[0]),noteToPitch(array[1]),array[2].split(" "), MyMIDI) writeToFile(array[3].rstrip('\n'), MyMIDI) MyMIDI = None else: print "Enter first note in sequence: " firstnote = noteToPitch(raw_input()) # process first note print "Enter last note in sequence: " lastnote = noteToPitch(raw_input()) # process last note print "Enter first note progression in the following format: " print "note/duration note/duration note/duration" progression = raw_input() # process note progression progression = progression.split(" ") makeProgression(firstnote,lastnote,progression) print "Enter file name: " filename = raw_input() writeToFile(filename)
def create_midi_file(ensemble, tempo): num_players = len(ensemble.G) mf = MIDIFile(num_players) channel = 0 #all on the same channel? for node in ensemble.G.nodes(): # initialize new track track = node #track index is the same as node index time = 0 #start at beginning mf.addTrackName(track, time, "Player {}".format(node)) mf.addProgramChange(track, channel, time, 42) mf.addTempo(track, time, tempo) #get player object and get data player = ensemble.G.nodes[node]['player'] data = player.data #add notes from (# note time = 0 here) for pitch, volume, duration in data: mf.addNote(track, channel, pitch, time, duration, volume) time += duration return savefile(mf)
def keysToMidi(reducedKeys): # create your MIDI object mf = MIDIFile(1) # only 1 track track = 0 # the only track time = 0 # start at the beginning mf.addTrackName(track, time, "Sample Track") mf.addTempo(track, time, random.randint(80,250)) # add some notes channel = 0 volume = 100 duration = [0.25,0.5 ,1,2] for i in range(0,len(reducedKeys)): if not len(reducedKeys[i]) == 0: for j in range(0,len(reducedKeys[i])): offset=[0,12,-12,-24] note=reducedKeys[i][j] pitch=pitchNumber[note]+random.choice(offset) mf.addNote(track, channel, pitch, time, random.choice(duration), volume) time=time+1 with open("output.mid", 'wb') as outf: mf.writeFile(outf)
def save_midi(outfile, notes, tempo): melodi_track = 0 time = 0 midifile = MIDIFile(1) midifile.addTrackName(melodi_track, time, "MELODI") midifile.addTempo(melodi_track, time, tempo) channel = 0 melodi_volume = 100 for note in notes: onset = note[0] * (tempo / 60.) duration = note[1] * (tempo / 60.) # duration = 1 pitch = int(note[2]) midifile.addNote(melodi_track, channel, pitch, onset, duration, melodi_volume) print(outfile) binfile = open(outfile, 'wb') midifile.writeFile(binfile) binfile.close()
def __init__(self, filename = "score.mid", num_tracks = 16): # requires midiutil from midiutil.MidiFile import MIDIFile self.filename = filename self.score = MIDIFile(num_tracks) self.time = 0
class MidiFileOut: def __init__(self, numtracks = 16): self.score = MIDIFile(numtracks) self.track = 0 self.channel = 0 self.volume = 64 self.time = 0 def tick(self, ticklen): self.time += ticklen def noteOn(self, note = 60, velocity = 64, channel = 0, duration = 1): #------------------------------------------------------------------------ # avoid rounding errors #------------------------------------------------------------------------ time = round(self.time, 5) self.score.addNote(channel, channel, note, time, duration, velocity) def noteOff(self, note = 60, channel = 0): pass def writeFile(self, filename = "score.mid"): fd = open(filename, 'wb') self.score.writeFile(fd) fd.close()
def convertToMIDI(): # create your MIDI object midi_file = MIDIFile(1) # only 1 track track = 0 # the only track current_time = 0 # start at the beginning midi_file.addTrackName(track, current_time, "OMR Output") midi_file.addTempo(track, current_time, 120) channel = 0 for symbol in matched_symbols: #TODO check if the previous symbol is within a certain threshold x value of the current one, if so, don't play the current if "rest" in symbol.symbol_type: volume = 0 pitch = treble_notes["A4"] note_length = symbol.note_length else: volume = 100 pitch = treble_notes[symbol.pitch] note_length = symbol.note_length midi_file.addNote(track, channel, pitch, current_time, note_length, volume) current_time += note_length with open("output.mid", 'wb') as outf: midi_file.writeFile(outf)
class PatternWriterMIDI: def __init__(self, numtracks = 1): self.score = MIDIFile(numtracks) self.track = 0 self.channel = 0 self.volume = 64 def addTrack(self, pattern, tracknumber = 0, trackname = "track", dur = 1.0): time = 0 # naive approach: assume every duration is 1 # TODO: accept dicts or PDicts for note in pattern: if note is not None: self.score.addNote(tracknumber, self.channel, note, time, dur, self.volume) time += dur else: time += dur def addTimeline(self, timeline): # TODO: translate entire timeline into MIDI # difficulties: need to handle degree/transpose params # need to handle channels properly, and reset numtracks pass def writeFile(self, filename = "score.mid"): fd = open(filename, 'wb') self.score.writeFile(fd) fd.close()
def __init__(self, stringCount, tempo=120, name="MIDI Strings"): self.stringCount = stringCount self.midiData = MIDIFile(stringCount) self.name = name self.tempo = tempo for i in range(self.stringCount): self.midiData.addTrackName(i, 0,"String "+str(i+1)) # track, time, track name
class PatternWriterMIDI: def __init__(self, numtracks = 1): self.score = MIDIFile(numtracks) self.track = 0 self.channel = 0 self.volume = 64 def addTrack(self, pattern, tracknumber = 0, trackname = "track", dur = 1.0): time = 0 # naive approach: assume every duration is 1 # TODO: accept dicts or PDicts try: for note in pattern: vdur = Pattern.value(dur) if note is not None and vdur is not None: self.score.addNote(tracknumber, self.channel, note, time, vdur, self.volume) time += vdur else: time += vdur except StopIteration: # a StopIteration exception means that an input pattern has been exhausted. # catch it and treat the track as completed. pass def addTimeline(self, timeline): # TODO: translate entire timeline into MIDI # difficulties: need to handle degree/transpose params # need to handle channels properly, and reset numtracks pass def writeFile(self, filename = "score.mid"): fd = open(filename, 'wb') self.score.writeFile(fd) fd.close()
def testAddNote(self): MyMIDI = MIDIFile(1) MyMIDI.addNote(0, 0, 100, 0, 1, 100) self.assertEquals(MyMIDI.tracks[0].eventList[0].type, "note") self.assertEquals(MyMIDI.tracks[0].eventList[0].pitch, 100) self.assertEquals(MyMIDI.tracks[0].eventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].eventList[0].duration, 1) self.assertEquals(MyMIDI.tracks[0].eventList[0].volume, 100)
def initializeTrack(tempo=100, numTracks=15): """Create a song with the given tempo.""" song = MIDIFile(numTracks) time = 0 for track in range(numTracks): song.addTrackName(track, time, "Track " + str(track)) song.addTempo(track, time, tempo) return song
def play(request): global outputId json = simplejson.loads(request.POST.get('notes')) midiFile = MIDIFile(1) track = 0 time = 0 midiFile.addTrackName(track, time, "Sample Track") midiFile.addTempo(track, time, 120) channel = 0 volume = 100 string = "" for note in json['notes']: pitch = strToMidiPitch(note['pitch']) duration = note['duration'] start = note['start'] midiFile.addNote(track, channel, pitch, start, duration, volume) string += "added note " + note['pitch'] + ": " + str(pitch) + ", " binfile = open("/tmp/output.mid", 'wb') midiFile.writeFile(binfile) binfile.close() call(['fluidsynth', '-l', '-F', '/tmp/output_'+str(outputId)+'.wav', '/usr/share/sounds/sf2/FluidR3_GM.sf2', '/tmp/output.mid']) call(['lame', '--preset', 'standard', '/tmp/output_'+str(outputId)+'.wav', '/tmp/output_'+str(outputId)+'.mp3']) outputId += 1 return HttpResponse(outputId-1)
def midFile(melody): MyMIDI = MIDIFile(1) track = 0 time = 0 MyMIDI.addTrackName(track, time, "Vireo") MyMIDI.addTempo(track, time, 340) track = 0 channel = 0 time = 0 volume = 100 for i in melody: data = i.split() MyMIDI.addNote(track, channel, int(data[0].strip()), time, int(data[1].strip()), volume) time = time + int(data[1].strip()) midi = "" binfile = open("./static/test.mid", "wb") MyMIDI.writeFile(binfile) binfile.close() binfile = open("./static/test.mid", "rb") midi = binfile.read() binfile.close() return midi
def write_midi_file(self, file_object): """Writes midi generated from this tab to the given file object.""" # Throw an exception if there are note names for which we can't # determine the proper note numbers. unmappable_note_names = self.note_types.difference( self.note_name_to_number_map.keys()) if unmappable_note_names: raise UnmappableNoteNamesException(unmappable_note_names) midifile = MIDIFile(1) track = 0 channel = 9 duration = round(4.0 / self.divisions_in_bar, 10) # 4.0 is because midiutil's unit of time is the quarter note. midifile.addTrackName(track, 0, "") midifile.addTempo(track, 0, self._bpm) for note in self.walk_notes(): strike_type = note['strike_type'] volume = self._volume_for_strke_type(strike_type) if strike_type == 'r': pitch = GM_SPEC_NOTE_NAME_TO_NUMBER_MAP['Sticks'] else: pitch = self.note_name_to_number_map[note['note_type']] midifile.addNote(track, channel, pitch, note['time'], duration, volume) midifile.writeFile(file_object)
def playMIDI(x,counter,counter2, O): from midiutil.MidiFile import MIDIFile MyMIDI=MIDIFile(1, removeDuplicates=False, deinterleave=False) track=0 time=0 MyMIDI.addTrackName(track,time,"Sample") MyMIDI.addTempo(track,time,60) track=0 channel=0 a=North[x] b=East[x] c=West[x] averagex=round(((a+b+c)/3),0) pitchcalc=pitchnum(averagex) pitch=pitchcalc timecalc,O=deltatime(counter, O) time=2 duration=timecalc if counter2==0: volume=10*(int(round(math.pow(North[x],1.0/3)))) elif counter2==1: volume=10*(int(round(math.pow(East[x],1.0/3)))) elif counter2==2: volume=10*(int(round(math.pow(West[x],1.0/3)))) else: print("numcount error", counter2) volume=127 MyMIDI.addNote(track,channel,pitch,time,duration,volume) outcount=str(counter) numcount=str(counter2) binfile=open(outpath+"/output "+outcount+" "+numcount+".mid",'wb') MyMIDI.writeFile(binfile) print(counter,"\n",track,channel,pitch,time,duration,volume) binfile.close() return O
def saveMIDI(filename, noteOnsets, melody, tempo, Fs, hopSize): barOnsets = (noteOnsets*hopSize/float(Fs))*(tempo/60) #Onsets dado en barra notes = quantizeNote(melody) track = 0 time = 0 MIDI = MIDIFile(1) # Add track name and tempo. MIDI.addTrackName(track,time,"MIDI TRACK") MIDI.addTempo(track,time,tempo) channel = 0 volume = 100 for i in range(np.size(barOnsets)): pitch = notes[noteOnsets[i]+1] #leer el pitch en el siguiente frame al onset if pitch > 0: time = barOnsets[i] if i == np.size(barOnsets)-1: duration = 1 else: duration = barOnsets[i+1]-barOnsets[i] MIDI.addNote(track,channel,pitch,time,duration,volume) # And write it to disk. binfile = open(filename, 'wb') MIDI.writeFile(binfile) binfile.close()
def matrix_to_midi(notes, filename = 'matrix.mid', tempo = 60): """ Simplify midi generation note format: PITCH|START|DURATION|VOLUME """ # Midi file with one track mf = MIDIFile(1) track = 0 time = 0 mf.addTrackName(track, time, filename[7:-4]) # Default # FIXME tempo -- time relation is not well defined mf.addTempo(track, time, tempo) channel = 0 time_per_tick = 2**-5 for note in notes: pitch = note[0] start = note[1] * time_per_tick stop = note[2] * time_per_tick vol = note[3] mf.addNote(track, channel, pitch, start, stop, vol) # Save as file with open(filename, 'wb') as fout: mf.writeFile(fout)
def create_midi(tempo, data): print 'Converting to MIDI.' song = MIDIFile(1) song.addTempo(0, 0, tempo) grouped = [(note, sum(1 for i in g)) for note, g in groupby(data)] time = 0 for note, duration in grouped: add_note(song, 0, note, time, duration) time += duration return song
def testSysEx(self): MyMIDI = MIDIFile(1) MyMIDI.addSysEx(0, 0, 0, struct.pack(">B", 0x01)) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, "SysEx") self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[0])[0], 0x00) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[1])[0], 0xF0) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[2])[0], 3) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[3])[0], 0x00) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[4])[0], 0x01) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[5])[0], 0xF7)
def reset_track(self): if self.track: del self.track self.track = None track = MIDIFile(1) track.addTrackName(0, 0, "beatfruit-recording") # FIXME: Use a nicer name, template it and include timestamp??? track.addTempo(0, 0, 120) # FIXME: Will impliment tempo changes later! self.track = track self.events = [] self.chans = {} self.last_timestamp = None self.base_time = None
def run(self): inputObj = self.get_input("input") #obiekt interfejsu wejściowego outputGraph = self.get_output("outputGraph") #obiekt interfejsu wyjściowego outputPitch = self.get_output("outputPitch") #obiekt interfejsu wyjściowego prev_note = 0 #init midi track = 0 time = 0 MyMIDI = MIDIFile(1) MyMIDI.addTrackName(track,time,"Sample Track") MyMIDI.addTempo(track,time,120) try: while self.running(): data_input = inputObj.read() N = data_input["N"] audioData = base64.b64decode(data_input["data"]) MAX_y = data_input["MAX_y"] y = np.array(struct.unpack("%dh" % (N * CHANNELS), audioData)) / MAX_y y_L = y[::2] y_R = y[1::2] Y_L = np.fft.fft(y_L, nFFT) Y_R = np.fft.fft(y_R, nFFT) # Łączenie kanałów FFT, DC - prawy kanał Y = abs(np.hstack((Y_L[-nFFT/2:-1], Y_R[:nFFT/2]))) samples = np.fromstring(audioData, dtype=np.int16) #wyliczenie dzwieku rawnote = analyse.musical_detect_pitch(samples) if rawnote is not None: note = np.rint(rawnote) #wyślij nutę na wyjście outputPitch.send(note) if note != prev_note: #MyMIDI.addNote(track,channel,pitch,time,duration,volume) MyMIDI.addNote(0,0,note,time,1,100) time+=1 prev_note = note output = {"db_table": list(Y)} outputGraph.send(output) #save midi on exit except: binfile = open("output.mid", 'wb') MyMIDI.writeFile(binfile) binfile.close()
def main(): if len(sys.argv) is 1: return song_descriptor_path = sys.argv[1] with open(song_descriptor_path, 'r') as f: read_data = f.read() song_descriptor = json.loads(read_data) midi_file = MIDIFile(len(song_descriptor['tracks'])) for track in song_descriptor['tracks']: make_midi(midi_file, track) with open("test.mid", 'wb') as outf: midi_file.writeFile(outf)
def playingmusic(O): from midiutil.MidiFile import MIDIFile MyMIDI=MIDIFile(1, removeDuplicates=False, deinterleave=False) track=0 time=0 MyMIDI.addTrackName(track,time,"Sample") MyMIDI.addTempo(track,time,120) for x in range(0,3000): counter=x for midout in range(0,3): O,MyMIDI,vol,pitch,time=playMIDI(x,counter, midout, O, MyMIDI) print(counter, midout, pitch, vol, time) return O,MyMIDI
def testDeinterleaveNotes(self): MyMIDI = MIDIFile(1) MyMIDI.addNote(0, 0, 100, 0, 2, 100) MyMIDI.addNote(0, 0, 100, 1, 2, 100) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, "NoteOn") self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, "NoteOff") self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time, 128) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].type, "NoteOn") self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].type, "NoteOff") self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].time, 256)
def create_midi(frequency): my_midi = MIDIFile(1) track = 0 channel = 0 pitch = 69 + 12 * log(max(frequency) / 440, 2) time = 0 duration = 1 volume = 100 my_midi.addTempo(track, time, 120) my_midi.addNote(track, channel, pitch, time, duration, volume) return my_midi
def testUniversalSysEx(self): MyMIDI = MIDIFile(1) MyMIDI.addUniversalSysEx(0, 0, 1, 2, struct.pack(">B", 0x01)) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, "UniversalSysEx") self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[0])[0], 0x00) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[1])[0], 0xF0) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[2])[0], 6) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[3])[0], 0x7E) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[4])[0], 0x7F) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[5])[0], 0x01) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[6])[0], 0x02) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[7])[0], 0x01) self.assertEquals(struct.unpack(">B", MyMIDI.tracks[0].MIDIdata[8])[0], 0xF7)
class Generator: def __init__(self, tempo = 120): self.midi_file = MIDIFile(1) self.midi_file.addTrackName(0, 0, "track") self.midi_file.addTempo(0, 0, tempo) self.current_time = 1 def add_pause(self, length = 1): self.current_time = self.current_time + length def add_chord(self, base, notes, length = 1): for note in notes: self.midi_file.addNote(0, 0, base + note, self.current_time, length, VOLUME_TABLE[len(notes)]) self.add_pause(length) def add_pattern(self, base, pattern): for item in pattern: length = item[len(item) - 1] self.add_chord(base, item[0 : len(item) - 1], length) def write(self, filename): output_file = open(filename, 'wb') self.midi_file.writeFile(output_file) output_file.close()
class midiFile: """ Allows MIDI files to be gradually built up. On creation, a MIDI file track is created, and notes are added through calls to addNote. The file can be saved through a call to writeFile. More information on the library being used at: http://www.emergentmusics.org/mididutil-class-reference """ def __init__(self, trackName, maxPackageDepth, bpm): self.state = MIDIFile(1) #Number of tracks. self.time = 0 self.track = 0 self.state.addTempo(self.track,self.time,bpm) self.maxPackageDepth = maxPackageDepth self.minPitch = 0 self.maxPitch = 127 def setPitchRange(self, min, max): """ Set the range (somewhere between 0-127) that will be used in assigning pitch to notes, which is based on package depth. """ self.minPitch = min self.maxPitch = max def addNote(self, depth, instrument, duration): """ Adds a new note to the MIDI file. Increments the time by 1 on addition of every note. depth: Package structure depth. Used to determine the pitch of the note. instrument: Number from 0-127 (see: http://en.wikipedia.org/wiki/General_MIDI#Program_change_events) duration: Number of beats note should be played over. """ channel = 0 pitch = getPitch(depth, self.maxPackageDepth, self.minPitch, self.maxPitch) volume = 127 logging.info("Adding note, with instrument {0}, pitch {1}, duration {2}".format(instrument, pitch, duration)) self.state.addProgramChange(self.track,channel, self.time, instrument) self.state.addNote(0,channel,pitch,self.time,duration,volume) self.time+=1 def writeFile(self, savePath): """ Write the current state of the MIDI file to disk. savePath: Name+Path of the MIDI file to be saved. """ binfile = open(savePath, 'wb') self.state.writeFile(binfile) binfile.close()
def __init__(self, filename = "score.mid", numtracks = 1): from midiutil.MidiFile import MIDIFile self.score = MIDIFile(numtracks) self.track = 0 self.channel = 0 self.volume = 64
def __init__(self, numtracks=16): from midiutil.MidiFile import MIDIFile self.score = MIDIFile(numtracks) self.track = 0 self.channel = 0 self.volume = 64 self.time = 0
def __init__(self, note_file): self.volume = 100 self.channel = 0 self.note_file = note_file self.set_note_list() self.set_track_info() #===== Initiate MIDI file object with n_track tracks =====# self.mf = MIDIFile(self.n_track)