def mat2midi(mat, name, SampleRate):
    from midiutil.MidiFile import MIDIFile  #incase
    import numpy as np
    [a, b] = mat.shape
    tStart = [0]
    out_midi = MIDIFile(1)
    track = 0
    time = 0
    tempo = 120
    out_midi.addTrackName(track, time, "output track")
    out_midi.addTempo(track, time, tempo)
    nTrack = 1
    for i in range(0, a):
        ind = [x for x in range(0, b - 2) if mat[i][x] != 0]
        while len(ind) > nTrack:
            out_midi.addTrackName(nTtrack, time, "output track")
            out_midi.addTempo(nTrack, time, tempo)
            nTrack = nTrack + 1
        dur = (mat[i][-2]) / SampleRate
        for k in range(0, len(ind)):
            pit = ind[k]
            channel = int(mat[i][-1])
            vol = int(mat[i][ind[k]])
            out_midi.addNote(k, channel, pit, tStart[-1], dur, vol)
        tStart.append(tStart[-1] + dur)
    filename = "../output/" + name + ".mid"
    with open(filename, 'wb') as file:
        out_midi.writeFile(file)
    return (out_midi)
Пример #2
0
	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)
Пример #3
0
def make_song_file(mood,key,syllables):
    # create the MIDIFile object with 1 track
    MyMIDI = MIDIFile(1)
    if (mood == 'mood1'):
        mood = pass1
    elif (mood == 'mood2'):
        mood = happy1
    elif (mood == 'mood3'):
        mood = cool1

    # 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,100)

    key = key%12
    MyMIDI = add_chords(MyMIDI,mood,key)
    MyMIDI = add_notes(MyMIDI,syllables,key,mood)

    # and write it to disk.
    binfile = open("song.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
Пример #4
0
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
Пример #5
0
def MIDI_VV(mf, noteLengths1_VV, noteLengths2_VV, noteLengths3_VV,
            currentNote1_VV, currentNote2_VV, currentNote3_VV):
    if mf is None:
        mf = MIDIFile(3)  #3 tracks
        startTime = 0  #begint bij het begin
        track = 0
        mf.addTrackName(track, startTime, "5/4 Beat")
        mf.addTempo(track, startTime, BPM)
        return MIDI_VV(mf, noteLengths1_VV, noteLengths2_VV, noteLengths3_VV,
                       currentNote1_VV, currentNote2_VV, currentNote3_VV)

    if len(noteLengths1_VV) == 0:
        print("...")
    else:
        track = 0  #eerste track
        channel = 10  #percussie
        volume = 100
        instrument = 35  #kick
        time = currentNote1_VV  #startpunt noot
        duration = noteLengths1_VV.pop(0)  #1e nootlengte uit de lijst
        mf.addNote(track, channel, instrument, time, duration,
                   volume)  #voeg noot toe aan midifile
        currentNote1_VV += duration
        return MIDI_VV(mf, noteLengths1_VV, noteLengths2_VV, noteLengths3_VV,
                       currentNote1_VV, currentNote2_VV, currentNote3_VV)

    if len(noteLengths2_VV) == 0:
        print("...")
    else:
        track = 0  #tweede track (voor losse tracks gebruik 1)
        startTime = 0
        channel = 10  #percussie
        volume = 100
        instrument = 38  #snare
        time = currentNote2_VV  #startpunt noot
        duration = noteLengths2_VV.pop(0)  #1e nootlengte uit de lijst
        mf.addNote(track, channel, instrument, time, duration, volume)
        currentNote2_VV += duration
        return MIDI_VV(mf, noteLengths1_VV, noteLengths2_VV, noteLengths3_VV,
                       currentNote1_VV, currentNote2_VV, currentNote3_VV)

    if len(noteLengths3_VV) == 0:
        print("Done")

        output_file = input("Name MIDI-file: ")
        #write to disk
        with open("output.mid", 'wb') as output_file:
            mf.writeFile(output_file)
    else:
        track = 0  #derde track (voor losse tracks gebruk 2)
        startTime = 0
        channel = 10  #percussie
        volume = 100
        instrument = 42  #hihat
        time = currentNote3_VV  #startpunt noot
        duration = noteLengths3_VV.pop(0)  #1e nootlengte uit de lijst
        mf.addNote(track, channel, instrument, time, duration, volume)
        currentNote3_VV += duration
        return MIDI_VV(mf, noteLengths1_VV, noteLengths2_VV, noteLengths3_VV,
                       currentNote1_VV, currentNote2_VV, currentNote3_VV)
Пример #6
0
def pixels_to_midi2():
    pix = get_image_data("small.jpg")
    mf = MIDIFile(1)
    track = 0
    time = 0
    channel = 0
    volume = 100
    mf.addTrackName(track, time, "Sample")
    mf.addTempo(track, time, 1000)
    for i in xrange(len(pix)):
        if i >= len(pix) - 4:
            break
        p1 = rgb_to_midi(pix[i])
        p2 = rgb_to_midi(pix[i + 1])
        p3 = rgb_to_midi(pix[i + 2])
        duration = 1
        if time % 4 == 0:
            mf.addNote(track, channel, p1, time, 4, 120)
            mf.addNote(track, channel, p2, time, 4, 120)
            mf.addNote(track, channel, p3, time, 4, 120)
        else:
            mf.addNote(track, channel, p1, time, duration, 50)
        time += 1
    with open("small.mid", 'wb') as outf:
        mf.writeFile(outf)
Пример #7
0
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)
Пример #8
0
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 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
Пример #10
0
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)
Пример #11
0
def MidiFileCreator(melody,song):  
    bpm = melody['bpm']
    pitches = melody['pitches']
    parts = [t.split('.') for t in melody['times']]
    times = [4*int(l)+int(r)-1 for l,r in parts]
    durations = melody['durations']
    chord_pitches = song['chord_pitches']
    chord_times = song['chord_times']
    chord_center = song['chord_center']
    ListOfRelativeChordVoicings = song['chord_pitches']
    token = melody['token']
    MyMIDI = MIDIFile(1)
    track = 0
    channel = 0
    time = 0
    duration = 4
    volume = 100
    MyMIDI.addTrackName(track,time,"Herp derp")
    MyMIDI.addTempo(track,time,bpm)
    #Sends Chords to MIDI
    root = int(chord_center)
    for chord in ListOfRelativeChordVoicings:
        for note in chord:
            Intnote = int(note + root)
            MyMIDI.addNote(track,channel,Intnote,time,duration,volume)
        time = time + 4   
    for note,time in zip(pitches,times):
        MyMIDI.addNote(track,channel,int(note),int(time),1,volume)
    binfile = open(base + "static/songs/" + token + ".mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
    return "blah"
Пример #12
0
    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
Пример #13
0
    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 convert_to_midi(input_file, output_file):
    predict_cnn(input_file)
    os.system(
        f"CNNOnsetDetector single {input_file} -o {CONVERTER_FOLDER}/onsets.txt"
    )
    onsets = np.loadtxt(f"{CONVERTER_FOLDER}/onsets.txt")
    frames = np.loadtxt(f"{CONVERTER_FOLDER}/result.txt")
    notes = []

    for i in range(onsets.shape[0]):
        onsets[i] = int(onsets[i] * 20)

    frames = np.loadtxt(f"{CONVERTER_FOLDER}/result.txt")
    notes = []

    for i in onsets:
        i = int(i)
        for n in range(88):
            if i + 2 < frames.shape[0]:
                if (frames[i][n] > p_onset or frames[i - 1][n] > p_onset
                        or frames[i + 1][n] > p_onset
                        or frames[i + 2][n] > p_onset
                        or frames[i - 2][n] > p_onset
                        or frames[i + 3][n] > p_onset
                        or frames[i - 3][n] > p_onset):
                    x = i
                    while x < frames.shape[0] and frames[x][n] > p_offset:
                        x = x + 1
                    if x - i > 1:
                        on_time = float(i / 20)
                        off_time = float(x / 20)

                        notes.append((n + 21, on_time, off_time))
                        for p in range(i, x):
                            frames[p][n] = 1000

    # plt.imshow(np.transpose(frames)[:, 200:400])
    # plt.title("final transcription")
    # plt.show()

    notes = sorted(notes, key=itemgetter(2, 0))

    notes_new = []
    for i in range(len(notes) - 2):
        if i == 0:
            notes_new.append(notes[i])
        if notes[i + 1][0] != notes[i][0]:
            notes_new.append(notes[i + 1])

    output = MIDIFile(1)
    track = 0
    channel = 0
    volume = 100
    output.addTrackName(track, 0, "Track 0")
    for note in notes_new:
        output.addNote(track, channel, note[0], note[1], note[2] - note[1],
                       volume)
    midi = open(output_file, 'wb')
    output.writeFile(midi)
    midi.close()
Пример #15
0
def midiwrite(outfile, notes, tempo):

    track = 0
    time = 0
    midifile = MIDIFile(1) # Just one track for now
    channel = 0
    volume = 100
    program = 1 # Bright piano
    
    # Add track name and tempo.
    midifile.addTrackName(track, time, "Synth Track")
    midifile.addTempo(track, time, tempo)
    midifile.addProgramChange(track, channel, time, program)

    for note in notes:
        onset = note[0] * (tempo/60.)
        duration = note[1] * (tempo/60.)
        # duration = 1
        pitch = note[2]
        midifile.addNote(track, channel, pitch, onset, duration, volume)

    # And write it to disk.
    binfile = open(outfile, 'wb')
    midifile.writeFile(binfile)
    binfile.close()
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
Пример #17
0
def test_one_text_column():
    '''
    A data frame with a single integer column
    should be converted correctly.
    '''
    expected = MIDIFile(1)
    expected.addTrackName(0,0,"vocals")
    expected.addTempo(0,0,120)
    for time,note in enumerate([38, 40, 42, 43]):
        expected.addNote(0,0,note,time,1,100)

    df = pandas.DataFrame([
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'badger'},
        {'vocals':'mushroom'},
        {'vocals':'mushroom'},
    ])
    observed = df_to_midi(df, bpm = 120)

    n.assert_equal(observed, expected)
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()    
Пример #19
0
def generate(n,
             program,
             suffix,
             sf="/usr/share/sounds/sf2/FluidR3_GM.sf2",
             volume=100):
    MyMIDI = MIDIFile(2)
    track = 0
    time = 0
    MyMIDI.addTrackName(track, time, "Test")
    MyMIDI.addTempo(track, time, 30)
    track = 0
    channel = 0
    time = 0
    duration = 2.0
    MyMIDI.addProgramChange(track, channel, 0, program)
    MyMIDI.addNote(track, channel, plist[n], 0, duration, volume)
    binfile = open("output.mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()

    os.system("fluidsynth %s output.mid -F output.wav --sample-rate 1000" % sf)
    os.system("lame -V 7 output.wav sound%d%s.mp3" % (n, suffix))
    #	os.system("avconv -i output.wav  -acodec sound%d%s.aac" % (n, suffix))
    os.system("rm output.mid")
    #	os.system("mplayer output.wav")
    os.system("mv output.wav sound%d%s.wav" % (n, suffix))
Пример #20
0
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)
Пример #21
0
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()
Пример #22
0
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()
Пример #23
0
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()
Пример #24
0
        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)
Пример #25
0
    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
Пример #26
0
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)
Пример #27
0
 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)
Пример #28
0
    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)
Пример #29
0
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)
Пример #30
0
def MidiFileCreator(melody, song):
    bpm = melody['bpm']
    pitches = melody['pitches']
    parts = [t.split('.') for t in melody['times']]
    times = [4 * int(l) + int(r) - 1 for l, r in parts]
    durations = melody['durations']
    chord_pitches = song['chord_pitches']
    chord_times = song['chord_times']
    chord_center = song['chord_center']
    ListOfRelativeChordVoicings = song['chord_pitches']
    token = melody['token']
    MyMIDI = MIDIFile(1)
    track = 0
    channel = 0
    time = 0
    duration = 4
    volume = 100
    MyMIDI.addTrackName(track, time, "Herp derp")
    MyMIDI.addTempo(track, time, bpm)
    #Sends Chords to MIDI
    root = int(chord_center)
    for chord in ListOfRelativeChordVoicings:
        for note in chord:
            Intnote = int(note + root)
            MyMIDI.addNote(track, channel, Intnote, time, duration, volume)
        time = time + 4
    for note, time in zip(pitches, times):
        MyMIDI.addNote(track, channel, int(note), int(time), 1, volume)
    binfile = open(base + "static/songs/" + token + ".mid", 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
    return "blah"
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)
Пример #32
0
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()
Пример #33
0
def save_midi(seq,path):
    mf = MIDIFile(4)   # only 1 track
    track = 1          # the only track

    time = 0    # start at the beginning
    mf.addTrackName(track, time, "Sample Track")
    mf.addTempo(track, time, 120)

    # add some notes
    channel = 1
    volume = 100

    pitch = 60           # C4 (middle C)
    time = 0             # start on beat 0
    duration = 1         # 1 beat long
    mf.addNote(0, channel, pitch, time, duration, volume)

    pitch = 20          # E4
    time = 2             # start on beat 2
    duration = 1         # 1 beat long
    mf.addNote(2, channel, pitch, time, duration, volume)

    pitch = 67           # G4
    time = 4             # start on beat 4
    duration = 1         # 1 beat long
    mf.addNote(3, channel, pitch, time, duration, volume)

    # write it to disk
    with open("output.mid", 'wb') as outf:
        mf.writeFile(outf)
Пример #34
0
def convertNotesTomidifile(notes_list, output_file_name):
    # converts and stores the midi file in the folder results

    # create your MIDI object
    mf = MIDIFile(1)  # 4 tracks

    time = 0  # start at the beginning
    beats_per_minute = 120

    mf.addTrackName(0, time, "Track 1")
    mf.addTempo(0, time, beats_per_minute)

    # initialize a list which stores notes, and only adds them to the midi after the full duration is known
    note_storage = Note()

    max_iter = 1000
    i = 0
    for note in notes_list:
        i += 1
        track_pitch = int(note)
        current_note = note_storage
        if track_pitch == current_note.pitch:
            current_note.add_dur()
            note_storage = current_note
        else:
            add_note_to_track(0, current_note, mf)
            note_storage = Note(time, track_pitch)
        time += tick_length  # move 1/4 beat into the future

    # After text file ends, add the remaining notes
    add_note_to_track(0, note_storage, mf)

    # write it to disk
    with open("results/" + output_file_name + ".mid", 'wb') as outf:
        mf.writeFile(outf)
Пример #35
0
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()
Пример #36
0
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
Пример #37
0
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()
Пример #38
0
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 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")
Пример #40
0
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)
Пример #41
0
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)
Пример #42
0
def make_song_file(mood, key, syllables):
    # create the MIDIFile object with 1 track
    MyMIDI = MIDIFile(1)
    if mood == "mood1":
        mood = pass1
    elif mood == "mood2":
        mood = happy1
    elif mood == "mood3":
        mood = cool1

    # 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, 100)

    key = key % 12
    MyMIDI = add_chords(MyMIDI, mood, key)
    MyMIDI = add_notes(MyMIDI, syllables, key, mood)

    # and write it to disk.
    binfile = open("song.mid", "wb")
    MyMIDI.writeFile(binfile)
    binfile.close()
Пример #43
0
class Midi:
    """Musique midi"""
    def __init__(self, partition, titre, tempo):
        # Définition des paramètres MIDI.
        piste = 0
        temps = 0
        self.tempo = tempo / 2
        self.sortiemidi = MIDIFile(1, file_format=1)
        # Nom de la piste.
        self.sortiemidi.addTrackName(piste, temps, sansaccents(titre))
        # Tempo.
        self.sortiemidi.addTempo(piste, temps, self.tempo)
        # Instrument (74 : flûte).
        self.sortiemidi.addProgramChange(piste, 0, temps, 74)
        self.traiter_partition(partition, piste, temps)

    def traiter_partition(self, partition, piste, temps):
        """Création des évènements MIDI"""
        transposition = partition.transposition
        channel = 0
        volume = 127
        for mot in partition:
            for i, syllabe in enumerate(mot):
                syl = str(syllabe)
                if i + 1 < len(mot):
                    syl = syl + '-'
                for j, note in enumerate(
                        notes for notes in syllabe.musique
                        if isinstance(notes, Note)
                ):
                    pitch = note.hauteur + transposition
                    duree = int(note.duree)
                    self.sortiemidi.addTempo(
                        piste, temps, (self.tempo * duree / note.duree)
                    )
                    self.sortiemidi.addNote(
                        piste,
                        channel,
                        pitch,
                        temps,
                        duree / 2,
                        volume
                    )
                    if j == 0:
                        self.sortiemidi.addText(
                            piste,
                            temps,
                            syl
                        )
                    temps += duree / 2

    def ecrire(self, chemin):
        """Écriture effective du fichier MIDI"""
        with (
            open(sys.stdout.fileno(), 'wb')
            if chemin == '-'
            else open(chemin, 'wb')
        ) as sortie:
            self.sortiemidi.writeFile(sortie)
Пример #44
0
    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()
Пример #45
0
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
Пример #46
0
 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 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
Пример #48
0
def convertToMIDI(piece):
    mfile = MIDIFile(1)
    track = 0
    time = 0
    tempo = 160

    mfile.addTrackName(track, time, "test")
    mfile.addTempo(track, time, tempo)

    channel = 0
    volume = 100

    # Actual magic happens here
    i = 0
    while i < len(piece)-1:
        # Get the corresponding pitch for the note
        pitch = mapping[piece[i][0]]
        diff = int(piece[i][-1]) - 4
        pitch += diff * 12

        # If we're dealing with a continued note
        if piece[i] == piece[i+1]:
            n = i
            duration = 0
            
            # Keep increasing the duration by 2 for
            # every consecutive matching note
            while piece[n] == piece[n+1]:
                #print n
                duration += 2
                if n+1 == len(piece):
                    break
                # Single note duration is 2
                n += 1
            mfile.addNote(track, channel, pitch, i*2, duration, volume)
            i = n

        # If we're dealing with a single note, add it
        else:
            mfile.addNote(track, channel, pitch, i*2, 2, volume)

            # If we're on the penultimate note,
            # add the last note too
            if i == len(piece) - 1:
                pitch = mapping[piece[i+1]]
                mfile.addNote(track, channel, pitch, i*2, 2, volume)
        i += 1

    bfile = open("output.mid", "wb")
    mfile.writeFile(bfile)
    bfile.close()
Пример #49
0
def WriteMidi(notes, tempo, file):
    MyMIDI = MIDIFile(1)

    MyMIDI.addTrackName(0,0,"Sample Track")
    MyMIDI.addTempo(0,0,tempo)

    time= 0
    for (name, d, length) in notes:
        MyMIDI.addNote(0,0,60,time,length*4,100)
        time+= length*4

    binfile = open(file, 'wb')
    MyMIDI.writeFile(binfile)
    binfile.close()
Пример #50
0
def write_midi(filename, sequence):
    filename = "music/"+filename
    midi = MIDIFile(1)
    track = 0
    start_time = 0
    midi.addTrackName(track, start_time, filename[:-4])
    tempo = random.randrange(120, 480)
    midi.addTempo(track, start_time, tempo)
    for seq in range(len(sequence)):
        for note in sequence[seq]:
            midi.addNote(track, 9, note.pitch, note.time, note.duration, note.volume)
        # midi.addProgramChange(0, seq, 0, instrList[seq])
    f = open(filename, 'w')
    midi.writeFile(f)
    f.close()
Пример #51
0
def write_song(song, dest, tempo=240):
    num_channels = len(song)
    midi_scratch_file = MIDIFile(num_channels)
    for i in range(0, num_channels):
        midi_scratch_file.addTrackName(i, 0, "Pop Flute {0}".format(i))
        midi_scratch_file.addTempo(i, 0, tempo)
        time = 0
        for x in range(0, song_length(song)):
            duration = 0.5
            pitch = song[i][x]
            midi_scratch_file.addNote(i, i, pitch, time, duration, 100)
            time += duration

    bin_file = open(dest, 'w')
    midi_scratch_file.writeFile(bin_file)
    bin_file.close()
Пример #52
0
def handle_score(score):
    parts = score.findall('part-list/score-part')
    midiparts = []
    for part in parts:
        actualpart = score.find('part[@id="%s"]' % part.get('id'))
        tuning = handle_tuning(actualpart)
        trackname = gettext(part.find('part-name'))
        midipart = MIDIFile(1)
        midipart.addTrackName(0, 0, trackname)
        midipart.name = trackname
        for channel, _ in enumerate(tuning):
            midipart.addProgramChange(0, channel, 0, getint(part.find('.//midi-program')))
        midipart.addTempo(0, 0, 120)
        handle_measures(midipart, actualpart, tuning)
        midiparts.append(midipart)
    return midiparts
Пример #53
0
def write_midi(filename, sequence):
    filename = "markov/"+filename
    midi = MIDIFile(1)
    track = 0
    start_time = 0
    midi.addTrackName(track, start_time, filename[:-4])
    tempo = random.randrange(360, 480)
    midi.addTempo(track, start_time, tempo)
    midi.addProgramChange(0, 0, 0, 1)
    
    for i in range(len(sequence)):
        note = sequence[i]
        midi.addNote(track, 0, note.pitch, note.time, note.duration, note.volume)
    f = open(filename, 'w')
    midi.writeFile(f)
    f.close()
Пример #54
0
    def export_midi(self, file_path):
        """Export a MIDI file."""
        midi = MIDIFile(1)
        midi.addTrackName(0, 0, self.metadata.get('OTL'))
        midi.addTempo(0, 0, 80)

        for i, part in enumerate(self.parts):
            non_rests = [ d for d in part['data'] if d['pitch'] != 'r' ]
            for note in non_rests:
                midi.addNote(track=0, channel=i,
                             pitch=note['midinote'],
                             time=note['beat'],
                             duration=note['duration'],
                             volume=80)

        with open(file_path, 'wb') as binfile:
            midi.writeFile(binfile)
Пример #55
0
def writeMID(filename, tempo, notes):
	# 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,tempo)

	writeNotes(MyMIDI, notes)

	# And write it to disk.
	binfile = open(filename, 'wb')
	MyMIDI.writeFile(binfile)
	binfile.close()
Пример #56
0
def generate_mesure_pattern(pattern=[(1, 1, 0, 48), (3, 1, 1, 48), (5, 1, 2, 48), (7, 1, 3, 48)], gamme=0):

    # Create the MIDIFile Object with 1 track

    MyMIDI = MIDIFile(1)

    # Tracks are numbered from zero. Times are measured in beats.

    track = track

    time = 0

    # Add track name and tempo.

    MyMIDI.addTrackName(track, time, "Sample Track")

    MyMIDI.addTempo(track, time, 120)

    # Add a note. addNote expects the following information:

    track = track

    channel = 0

    # pitch = note generée

    time = 0

    duration = 1

    volume = 100

    # Now add the note.

    MyMIDI.addNote(track, channel, pitch, time, duration, volume)
    print("lapin")

    # And write it to disk.

    binfile = open("output.mid", "wb")

    MyMIDI.writeFile(binfile)

    binfile.close()
Пример #57
0
def patterns_to_midi_v2(patterns, midi_out):
  num_tracks = len(patterns)
  midi = MIDIFile(num_tracks)
  tempo = 120
  duration = 1

  # track, time, name
  midi.addTrackName(0, 0, "Track0")
  # track, time, tempo
  midi.addTempo(0, 0, tempo)

  for pattern_id, pattern in patterns.items():
    onsets = np.array([ i for i in range(len(pattern)) if pattern[i] == 1 ])
    
    for onset in onsets:
      midi.addNote(0, 0, pattern_id, onset, duration, 127)

  with open(midi_out, 'wb') as f:
    midi.writeFile(f)
Пример #58
0
def test_one_int_column():
    '''
    A data frame with a single integer column
    should be converted correctly.
    '''
    expected = MIDIFile(1)
    expected.addTrackName(0,0,"guitar")
    expected.addTempo(0,0,120)
    for time,note in enumerate([38, 40, 42, 43]):
        expected.addNote(0,0,note,time,1,100)

    df = pandas.DataFrame([
        {'guitar':38},
        {'guitar':40},
        {'guitar':42},
        {'guitar':43},
    ])
    observed = df_to_midi(df, bpm = 120)
    assert_midi_equal(observed, expected)
class Midi:
    def __init__(self):
        # Create the MIDIFile Object with 1 track
        self.midi = MIDIFile(1)

        # Tracks are numbered from zero. Times are measured in beats.
        track = 0
        time = 0

        # Add track name and tempo.
        self.midi.addTrackName(track,time,"Sample Track")
        self.midi.addTempo(track,time,120)

        self.timer = 0

    def add_note(self, pitch, duration, track = 0, channel = 0, volume = 100):
        # Now add the note.
        self.midi.addNote(track, channel, self.pitch_to_midi(pitch), self.timer, duration, volume)
        self.timer += duration*2

    def write(self):
        # And write it to disk.
        binfile = open("output.mid", 'wb')
        self.midi.writeFile(binfile)
        binfile.close()

    def pitch_to_midi(self, note):
        return {
            "A3" : 57,
            "B3" : 59,
            "C3" : 48,
            "D3" : 50,
            "E3" : 52,
            "F3" : 53,
            "G3" : 55,
            "A4" : 69,
            "B4" : 71,
            "C4" : 60,
            "D4" : 62,
            "E4" : 64,
            "F4" : 65,
            "G4" : 67,
        }[note]