def noteStateMatrixToMidi(statematrix, name="example"):
    statematrix = numpy.asarray(statematrix)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    span = upperBound - lowerBound
    #tickscale = 55
    tickscale = 110

    lastcmdtime = 0
    prevstate = [[0, 0] for x in range(span)]
    for time, state in enumerate(statematrix + [prevstate[:]]):
        offNotes = []
        onNotes = []
        for i in range(span):
            n = state[i]
            p = prevstate[i]
            if p[0] == 1:
                if n[0] == 0:
                    offNotes.append(i)
                elif n[1] == 1:
                    offNotes.append(i)
                    onNotes.append(i)
            elif n[0] == 1:
                onNotes.append(i)
        for note in offNotes:
            track.append(
                midi.NoteOffEvent(tick=(time - lastcmdtime) * tickscale,
                                  pitch=note + lowerBound))
            lastcmdtime = time
        for note in onNotes:
            track.append(
                midi.NoteOnEvent(tick=(time - lastcmdtime) * tickscale,
                                 velocity=40,
                                 pitch=note + lowerBound))
            lastcmdtime = time

        prevstate = state

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    midi.write_midifile("{}.mid".format(name), pattern)
예제 #2
0
def save_piece(piece, file_path):
    piece = np.asarray(piece)

    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    span = UPPER_BOUND - LOWER_BOUND
    tickscale = 55

    lastcmdtime = 0
    prevstate = [[0, 0] for x in range(span)]
    for time, state in enumerate(piece + [prevstate[:]]):
        offNotes = []
        onNotes = []
        for i in range(span):
            n = state[i]
            p = prevstate[i]
            if p[0] == 1:
                if n[0] == 0:
                    offNotes.append(i)
                elif n[1] == 1:
                    offNotes.append(i)
                    onNotes.append(i)
            elif n[0] == 1:
                onNotes.append(i)
        for note in offNotes:
            track.append(
                midi.NoteOffEvent(tick=(time - lastcmdtime) * tickscale,
                                  pitch=note + LOWER_BOUND))
            lastcmdtime = time
        for note in onNotes:
            track.append(
                midi.NoteOnEvent(tick=(time - lastcmdtime) * tickscale,
                                 velocity=40,
                                 pitch=note + LOWER_BOUND))
            lastcmdtime = time

        prevstate = state

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    midi.write_midifile(file_path, pattern)
예제 #3
0
    def hide(self, midi_file_name, message):

        result = None
        pattern = self.get_pattern(midi_file_name)
        number_of_tracks = len(pattern)

        # in case the midi file has no tracks (that means, no music)
        # we add one so we can add the hidden data there
        # this track will not have any Note events, so it will not add sound
        # If it does have one, we work with that track
        if number_of_tracks == 0:
            # Instantiate a MIDI Track (contains a list of MIDI events)
            track = midi.Track()
            # Append the track to the pattern
            pattern.append(track)

        # Now we need to add a termination line, so we know we need to stop reading
        # Instantiate a MIDI note off event, append it to the track
        off = midi.NoteOffEvent(tick=73, pitch=midi.G_3)
        pattern[0].insert(0, off)

        # Insert the hidden messages as Program change events at the start of the list.
        # (you could also add them at the end as the user will not detect them since
        # no sound would be comming out .... but it has one problem
        # If you want to verify the insertion
        # You have to scroll to the end of the file and check. If the midi file
        # is really big, this could be really time consuming)
        #
        # We cannot add them in the middle, since the change of instruments could be
        # noticeable

        channelToAlter = 16  # This channel might not even be used by any other event
        for char in message:
            number = ord(char)
            change_program = midi.ProgramChangeEvent(tick=0,
                                                     channel=channelToAlter,
                                                     data=[number])
            pattern[0].insert(0, change_program)

        on = midi.NoteOnEvent(tick=0, velocity=0, pitch=midi.G_3)
        pattern[0].insert(0, on)

        new_midi_file_name = "secret_in_" + midi_file_name
        self.save_midi_file(pattern, new_midi_file_name)
예제 #4
0
def noteStateMatrixToMidi(statematrix, name="example", span=span):
    statematrix = np.array(statematrix)
    print statematrix, len(statematrix.shape), statematrix.shape, span
    if not len(statematrix.shape) == 3:
        statematrix = np.dstack((statematrix[:, :span], statematrix[:, span:2*span], statematrix[:, 2*span:]))
    statematrix = np.asarray(statematrix)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    
    span = upperBound-lowerBound
    tickscale = 55
    
    lastcmdtime = 0
    prevstate = [[0,0,0] for x in range(span)]
    for time, state in enumerate(statematrix + [prevstate[:]]):  
        offNotes = []
        onNotes = []
        for i in range(span):
            n = state[i]
            p = prevstate[i]
            if (p[0])== 1:
                if (n[0]) == 0:
                    offNotes.append((i, n[2]))
                elif (n[1]) == 1:
                    offNotes.append((i, p[2]))
                    onNotes.append((i, n[2]))
            elif (n[0]) == 1:
                onNotes.append((i, n[2]))
        print onNotes
        for note in offNotes:
            track.append(midi.NoteOffEvent(tick=(time-lastcmdtime)*tickscale, velocity = (int(note[1]*50)+45)%128, pitch=note[0]+lowerBound))
            lastcmdtime = time
        for note in onNotes:
            track.append(midi.NoteOnEvent(tick=(time-lastcmdtime)*tickscale, velocity=(int(note[1]*50)+45)%128, pitch=note[0]+lowerBound))
            lastcmdtime = time
            
        prevstate = state
    
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    midi.write_midifile("{}.mid".format(name), pattern)
예제 #5
0
def notetomidi(notearray, i, style_code, reward):
    mini_len = 64
    note_len = mini_len

    #print (notearray)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    #style_code = #notearray[0]
    notearray = notearray[1:]
    if style_code == 2:  #hymn
        h, f = 3, 8
    elif style_code == 0:  #classical
        h, f = 0, 2
    elif style_code == 1:  #jazz
        h, f = 1, 6
    elif style_code == 3:  #vgm
        h, f = 0, 8
    else:
        h, f = 0, 5

    last_note = 0
    for n in notearray:
        if n == 1:
            note_len = note_len + mini_len
        elif int(n) > 1:
            if note_len == mini_len:
                note_len += mini_len * (random.randint(h, f))
            track.append(
                midi.NoteOnEvent(tick=note_len, channel=0, data=[last_note,
                                                                 0]))
            track.append(
                midi.NoteOnEvent(tick=0, channel=0, data=[n + 34, 110]))
            last_note = n + 34
            note_len = mini_len

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    style = ["classical", "jazz", "hymn", "vgm"]
    #print (style_code)

    midi.write_midifile(
        "example" + str(i) + style[style_code] + str(reward) + ".mid", pattern)
예제 #6
0
def text2midi(text,
              timing=[],
              scale=[0, 2, 4, 5, 7, 9, 11],
              name="example.mid",
              baselet="a",
              key=60,
              transformation=letter2note,
              space_func=skip_space,
              base_duration=100,
              delay=0,
              note_velocity=20,
              file_func=create_midi,
              **kwargs):

    text_length = len(text)
    timing_length = len(timing)

    if timing_length < text_length:
        dif = text_length - timing_length
        timing += dif * [1]
    elif timing_length > text_length:
        timing = timing[:text_length]

    pattern = midi.Pattern(resolution=320)
    track = midi.Track()
    pattern.append(track)
    for i in range(text_length):
        letter = text[i]
        if letter == ' ':
            on, off = space_func(timing[i], base_duration, delay,
                                 note_velocity)
        else:
            note = transformation(letter, scale, key, baselet, space_func)
            on, off = note_sound(note, timing[i], base_duration, delay,
                                 note_velocity)

        track.append(on)
        track.append(off)

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    file_func(name, pattern, **kwargs)
예제 #7
0
def sing(seq):
    '''
	It turns a sequence of pitches into a midi.
	You can alternate the resolution to change its speed.
	'''

    pattern = midi.Pattern()
    track = midi.Track()

    pattern.append(track)
    #resolution
    pattern.resolution = 200
    for note in seq:
        on = midi.NoteOnEvent(tick=0, velocity=50, pitch=note)
        track.append(on)
        off = midi.NoteOffEvent(tick=100, pitch=note)
        track.append(off)
    track.append(midi.EndOfTrackEvent(tick=1))
    midi.write_midifile("song.mid", pattern)
예제 #8
0
def noteStateMatrixToMidi(statematrix, name="example", span=span):
    statematrix = np.array(statematrix)
    if not len(statematrix.shape) == 3:
        statematrix = np.dstack((statematrix[:, :span], statematrix[:, span:]))
    statematrix = np.asarray(statematrix)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    
    span = upperBound-lowerBound
    tickscale = 55
    
    lastcmdtime = 0
    prevstate = [[0,0] for x in range(span)]
    for time, state in enumerate(statematrix + [prevstate[:]]):  
        offNotes = []
        onNotes = []
        for i in range(span):
            n = state[i]
            p = prevstate[i]
            if p[0] == 1:
                if n[0] == 0:
                    offNotes.append(i)
                elif n[1] == 1:
                    offNotes.append(i)
                    onNotes.append(i)
            elif n[0] == 1:
                onNotes.append(i)
        for note in offNotes:
            track.append(midi.NoteOffEvent(tick=(time-lastcmdtime)*tickscale, pitch=note+lowerBound))
            lastcmdtime = time
        for note in onNotes:
            track.append(midi.NoteOnEvent(tick=(time-lastcmdtime)*tickscale, velocity=40, pitch=note+lowerBound))
            lastcmdtime = time
            
        prevstate = state
    
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    path = os.getcwd()
    path = path+'\\gen'

    midi.write_midifile("{}\\{}.mid".format(path, name), pattern)
예제 #9
0
def main():
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    pitchs = [1, 3, 5, 1, 5, 6, 8, 8, 10, 8, 6, 5, 1, 3, -4, 1]
    pitchs = [p + 60 for p in pitchs]
    tempos = [2, 2, 2, 2, 2, 2, 4, 1, 1, 1, 1, 2, 2, 2, 2, 4]
    repeats = [4, 3, 6, 3]
    print('resolution = ', pattern.resolution)
    idx = 0
    tmp_pitchs = pitchs
    tmp_tempos = tempos
    pitchs, tempos = (list() for _ in range(2))
    for r in repeats:
        pitchs += tmp_pitchs[idx:idx + r] * 2
        tempos += tmp_tempos[idx:idx + r] * 2
        idx += r

    hmn = [0]
    pitchs = [tuple(p + i for i in hmn) for p in pitchs]
    for ps, t in zip(pitchs, tempos):
        for p in ps:
            track_append(track, ON, 0, p)
        for idx, p in enumerate(ps):
            track_append(track, OFF, 50 * t if idx == 0 else 0, p)

    # tempos = [2, 2, 2]
    # for p in pitchs:
    #   track_append(track, ON, 0, p)
    # track_append(track, OFF, 500, 61)

    # for p, t in zip(pitchs, [0]+tempos):
    # track_append(track, ON, 50*t, p)
    # track_append(track, OFF, 50*t, p)
    # for ps, t in zip(zip(pitchs, pitchs_2), tempos):
    #   track_append(track, ON, 0, ps[0])
    #   track_append(track, ON, 0, ps[1])
    #   track_append(track, OFF, 50*t, ps[0])
    #   track_append(track, OFF, 0, ps[1])
    track_append(track, EOF, tick=1)
    midi.write_midifile("tiger.mid", pattern)
def sequence_to_midi(state_matrix, filepath, meta_info=None):

    resolution, tempo_event = meta_info if meta_info else None

    pattern = midi.Pattern(resolution=resolution)
    track = midi.Track()
    pattern.append(track)
    if tempo_event:
        track.append(tempo_event)

    notes_on, _ = state_diff([0] * 128, state_matrix[0])
    for note in notes_on:
        track.append(midi.NoteOnEvent(tick=0, channel=0, data=note))

    current_state_index = 0
    while current_state_index < len(state_matrix):
        next_state_index = get_next_different_state(state_matrix,
                                                    current_state_index)
        ticks_elapsed = next_state_index - current_state_index

        current_state = state_matrix[current_state_index]
        next_state = state_matrix[next_state_index] if next_state_index < len(
            state_matrix) else [0] * 128
        notes_on, notes_off = state_diff(current_state, next_state)

        for note in notes_on:
            track.append(
                midi.NoteOnEvent(tick=ticks_elapsed, channel=0, data=note))

            ticks_elapsed = 0

        for note in notes_off:
            track.append(
                midi.NoteOffEvent(tick=ticks_elapsed, channel=0, data=note))
            ticks_elapsed = 0

        current_state_index = next_state_index

    track.append(midi.EndOfTrackEvent(tick=1))
    midi.write_midifile(filepath, pattern)

    return pattern
예제 #11
0
def flatten(pattern):
    # Takes a MIDI pattern (defined in the midi package) with multiple tracks
    # and returns a single track containing every event in the original pattern,
    # with absolute tick values instead of relative.

    # Copy the original pattern
    a = copy.copy(pattern)

    # Make the tick values absolute
    a.make_ticks_abs()

    # Make a new track, and append every event in every track of a.
    b = midi.Track()
    for track in a:
        for event in track:
            b.append(event)

    # Sort and output the result
    b.sort()
    return b
예제 #12
0
def mergeTrack(s):
    """
    Merge all tracks in s in a single one.
    """
    singletrack = midi.Track()
    events = []
    for i, track in enumerate(s):
        t = 0
        for event in track:
            t += event.tick
            if event.name in ['Note On', 'Note Off']:
                candidate = {'t': t, 'event': event}
                events.append(candidate)
    events = sorted(events, key=lambda k: k['t'])
    tick = 0
    for e in events:
        e['event'].tick = e['t'] - tick
        tick = e['t']
        singletrack.append(e['event'])
    return singletrack
예제 #13
0
def compile_notes(notes_list):
    """
    Takes in a list of Note objects and returns a playable midi track

    example use of midi library defined here:
    https://github.com/vishnubob/python-midi

    Follow installation instructions from Github readme to use.
    """
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    for note in notes_list:
        on = midi.NoteOnEvent(tick=0, velocity=70, pitch=note.getPitch())
        track.append(on)
        off = midi.NoteOffEvent(tick=100, pitch=note.getPitch())
        track.append(off)
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    midi.write_midifile("example.mid", pattern)
예제 #14
0
def note_list_to_midi(notes, start_pitch, tickscale = 1):
    """
    Converts a list of RelativeNotes to a MIDI track
    """
    track = midi.Track(tick_relative=False)
    pitch = start_pitch
    time = 0
    for note in notes:
        pitch, time, duration = note.get_absolute(pitch, time)
        #print "Writing midi, using time {}".format(time)
        if pitch > 0 and pitch < 128:
            track.append(midi.NoteOnEvent(tick=time * tickscale, pitch=pitch,
                                          velocity=60))
            track.append(midi.NoteOffEvent(tick=(time+duration) * tickscale,
                                           pitch=pitch))
    track.sort(key=lambda x: x.tick)
    track.append(midi.EndOfTrackEvent(tick=track[-1].tick + 1
                                      if len(track) else 0))
    track.make_ticks_rel()
    return track
예제 #15
0
def predictionToBasicMIDI(pred_mat, filename, slices_per_second=31.25):
    '''
    pred_mat: list of 88 np arrays, each of length num_slices
    filename: prefix to save MIDI file
    TEMPO: tempo for MIDI file to be created under
    '''
    TEMPO = 60
    TICKS_PER_BEAT = slices_per_second * 12
    NOTE_OFFSET = 9  # add to index to get MIDI pitch
    VELOCITY = 40  # constant velocity for each note

    pattern = midi.Pattern()
    pattern.resolution = TICKS_PER_BEAT
    track = midi.Track()
    track.make_ticks_abs()
    tempoEvent = midi.events.SetTempoEvent()
    tempoEvent.set_bpm(TEMPO)
    track.append(tempoEvent)
    pattern.append(track)
    noteOn = [0] * 88
    num_pitches, num_slices = pred_mat.shape
    print num_pitches, num_slices
    for t in range(num_slices):
        for pitch in range(num_pitches):
            state = pred_mat[pitch][t]
            midi_pitch = pitch + NOTE_OFFSET
            if state == 1 and noteOn[pitch] == 0:
                track.append(
                    midi.NoteOnEvent(tick=12 * t,
                                     pitch=midi_pitch,
                                     velocity=VELOCITY))
                noteOn[pitch] = 1
            elif state == 0 and noteOn[pitch] == 1:
                track.append(
                    midi.NoteOnEvent(tick=12 * t, pitch=midi_pitch,
                                     velocity=0))
                noteOn[pitch] = 0
    track.append(midi.EndOfTrackEvent(tick=12 * t))
    track.make_ticks_rel()
    print track[:10]
    midi.write_midifile(filename, pattern)
예제 #16
0
    def note_states_to_midi(self, statematrix, target_path):
        statematrix = np.array(statematrix)
        span = self.MAX_MIDI_NOTE - self.MIN_MIDI_NOTE
        if not len(statematrix.shape) == 3:
            statematrix = np.dstack((statematrix[:, :span], statematrix[:, span:]))
        statematrix = np.asarray(statematrix)
        pattern = midi.Pattern()
        track = midi.Track()
        pattern.append(track)

        tickscale = 55

        lastcmdtime = 0
        prevstate = [[0, 0] for x in range(span)]
        for time, state in enumerate(statematrix + [prevstate[:]]):
            offNotes = []
            onNotes = []
            for i in range(span):
                n = state[i]
                p = prevstate[i]
                if p[0] == 1:
                    if n[0] == 0:
                        offNotes.append(i)
                    elif n[1] == 1:
                        offNotes.append(i)
                        onNotes.append(i)
                elif n[0] == 1:
                    onNotes.append(i)
            for note in offNotes:
                track.append(midi.NoteOffEvent(tick=(time - lastcmdtime) * tickscale, pitch=note + lowerBound))
                lastcmdtime = time
            for note in onNotes:
                track.append(midi.NoteOnEvent(tick=(time - lastcmdtime) * tickscale, velocity=40, pitch=note + lowerBound))
                lastcmdtime = time

            prevstate = state

        eot = midi.EndOfTrackEvent(tick=1)
        track.append(eot)

        midi.write_midifile("{}.mid".format(target_path), pattern)
예제 #17
0
 def unparse(self, sequence, sp, tickscale=24, velocity=80):
     sequence = np.array(sequence)
     pattern = midi.Pattern()
     pattern.resolution = 480
     track = midi.Track()
     pattern.append(track)
     tickscale = tickscale
     lastcmdtime = 0
     prevstate = [0 for x in range(self.__pitch_span)]
     for time, state in enumerate(sequence):
         offNotes = []
         onNotes = []
         for i in range(self.__pitch_span):
             n = state[i]
             p = prevstate[i]
             if p == 1 and n == 0:
                 offNotes.append(i)
             elif p == 0 and n == 1:
                 onNotes.append(i)
             pass
         for note in offNotes:
             tick = (time - lastcmdtime) * tickscale
             pitch = note + self.__lowest_pitch
             event = midi.NoteOffEvent(tick=tick, pitch=pitch)
             track.append(event)
             lastcmdtime = time
         for note in onNotes:
             tick = (time - lastcmdtime) * tickscale
             pitch = note + self.__lowest_pitch
             event = midi.NoteOnEvent(tick=tick,
                                      velocity=velocity,
                                      pitch=pitch)
             track.append(event)
             lastcmdtime = time
             pass
         prevstate = state
         pass
     eot = midi.EndOfTrackEvent(tick=1)
     track.append(eot)
     midi.write_midifile(sp, pattern)
     pass
예제 #18
0
파일: MidiTools.py 프로젝트: jKlag/MeRLA
def create_track_from_notes(notes, res):
    track = midi.Track()
    prev_note = notes[0]

    # append first note
    on = midi.NoteOnEvent(tick=0, velocity=80, pitch=notes[0])
    track.append(on)
    delay = 0
    for note in notes[1:]:
        off = midi.NoteOffEvent(tick=res, pitch=prev_note)
        # rest
        if note == -1:
            delay += 1
        else:
            on = midi.NoteOnEvent(tick=res * delay, velocity=80, pitch=note)
            track.append(off)
            track.append(on)
            prev_note = note
            delay = 0

    return track
예제 #19
0
def main():
    midifiles = glob.glob(params.lstm_output + '/*.csv')
    
    # Define midi pattern parameters
    pattern = midi.Pattern()
    pattern.resolution = 70

    for midifile in midifiles:
        track = midi.Track()
        track.append(midi.SetTempoEvent(bpm = np.random.randint(10,20)))

        df = pd.read_csv(midifile, header=None)
        df = postprocess(df)
        # Decode output grid from LTSM into one full track of notes:
        track = decoder(track, df.values[:,0:])
        eot = midi.EndOfTrackEvent(tick = 1) #essential for the track to be turned into a readable midi file
        track.append(eot)
        # Translate track into midi file
        pattern.append(track)

    midi.write_midifile(params.midi_generated + params.artist + ".mid",  pattern)
예제 #20
0
def noteStateMatrixToMidi(statematrix, name="example"):
    lowerBound = 0
    upperBound = 128
    span = upperBound-lowerBound

    statematrix = np.array(statematrix)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    
    #span = upperBound-lowerBound
    tickscale = 55
    
    lastcmdtime = 0
    prevstate = [0 for x in range(span)]
    for time, state in enumerate(np.vstack((statematrix ,prevstate))): 
        offNotes = []
        onNotes = []
        for i in range(span):
            n = state[i]
            p = prevstate[i]
            if p == 1:
                if n == 0:
                    offNotes.append(i)
                elif n == 1:
                    pass
            elif n == 1:
                onNotes.append(i)
        for note in offNotes:
            track.append(midi.NoteOffEvent(tick=(time-lastcmdtime)*tickscale, pitch=note+lowerBound))
            lastcmdtime = time
        for note in onNotes:
            track.append(midi.NoteOnEvent(tick=(time-lastcmdtime)*tickscale, velocity=120, pitch=note+lowerBound))
            lastcmdtime = time
            
        prevstate = state
    
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    return pattern
예제 #21
0
def compose(sourceFile, outputFileName, length):
    markov = Markov(sourceFile)

    sequenceLength = markov.sequenceLength()

    # Build random beging of song
    notes = []
    for i in range(sequenceLength):
        notes.append(random.randint(50, 60))

    # Build list of notes
    while (len(notes) < length):
        newNote = markov.get(notes[-sequenceLength:])
        if newNote is not None:
            notes.append(int(newNote))
        else:
            print "INFO: No possible note found"
            del notes[-1]

    print "Song Composed:"
    print notes

    # Make patern into
    pattern = midi.Pattern()
    pattern.make_ticks_abs()
    track = midi.Track()
    pattern.append(track)

    for note in notes:
        on = midi.NoteOnEvent(tick=0, velocity=NOTE_VELOCITY, pitch=note)
        off = midi.NoteOffEvent(tick=NOTE_DURATION[get_rand_duration()],
                                pitch=note)
        track.append(on)
        track.append(off)

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    midi.write_midifile(outputFileName, pattern)

    print "Song written to file: %s" % outputFileName
예제 #22
0
def noteStateMatrixToMidi(statematrix, name="example", span=span):
    statematrix = np.array(statematrix)
    if not len(statematrix.shape) == 3:
        statematrix = np.dstack((statematrix[:, :span], statematrix[:, span:]))
    statematrix = np.asarray(statematrix)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    span = upperBound - lowerBound
    tickscale = 55

    lastcmdtime = 0
    prevstate = [[0, 0] for x in range(span)]
    for time, state in enumerate(statematrix):
        offNotes = []
        onNotes = []
        print(time)
        print(state)
        for i in range(span):
            n = state[0][i]
            print(n)
            if n == 1:
                onNotes.append(i)
        for note in offNotes:
            track.append(
                midi.NoteOffEvent(tick=(time - lastcmdtime) * tickscale,
                                  pitch=note + lowerBound))
            lastcmdtime = time
        for note in onNotes:
            track.append(
                midi.NoteOnEvent(tick=(time - lastcmdtime) * tickscale,
                                 velocity=40,
                                 pitch=note + lowerBound))
            lastcmdtime = time

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    midi.write_midifile("{}.midi".format(name), pattern)
예제 #23
0
def writeMIDI(dtseq, Tseq, pitchseq, path, label="1", tag="1", resolution=140):

    # Instantiate a MIDI Pattern (contains a list of tracks)
    pattern = midi.Pattern(format = 0, resolution = resolution)
    # Instantiate a MIDI Track (contains a list of MIDI events)
    track = midi.Track()
    # Append the track to the pattern
    pattern.append(track)
    tick = 0
    Events = []
    
    #Timing
    timeperbeat = 60. / 120#[s]
    timepertick = timeperbeat/resolution
    
    for dt, T, p in zip(dtseq, Tseq, pitchseq):
        if dt == 'START/END' or T == 'START/END' or p == 'START/END':
            break
        tick = tick + int(dt*resolution)
        Events.append({'t': tick, 'p': p, 'm': 'ON'})
        Events.append({'t': tick+int(T*resolution), 'p': p, 'm': 'OFF'})

    Events = sorted(Events, key=lambda k: k['t'])
    tick = 0
    for event in Events:
        if event['m'] == 'ON':
            e =  midi.NoteOnEvent(tick=event['t']-tick, velocity=90, pitch=event['p'])
        if event['m'] == 'OFF':
            e =  midi.NoteOffEvent(tick=event['t']-tick, velocity=90, pitch=event['p'])
        track.append(e)
        tick = event['t']
        

    # Add the end of track event, append it to the track
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    # Save the pattern to disk
    midi.write_midifile(path+label+"_"+tag+".mid", pattern)
    
    return pattern
예제 #24
0
def writeToMIDIFile(tracks, filepath):
    """Writes the tracks to a standard MIDI file"""
    pattern = midi.Pattern()
    pattern.resolution = GB_NOTE_RESOLUTION
    for t in tracks.values():
        if t['type'] == 'instrument':
            track = midi.Track()
            pattern.append(track)
            offs = []
            currentTime = 0
            # Go through each note in track interleaving into on/off events
            for n in t['notes']:
                # Insert note off events from queue
                while len(offs) > 0 and offs[0][0] < n['time']:
                    off = heapq.heappop(offs)
                    dif = off[0] - currentTime
                    currentTime = off[0]
                    offEvent = midi.NoteOffEvent(tick=dif,
                                                 velocity=60,
                                                 pitch=off[1])
                    track.append(offEvent)
                # Add note on
                dif = n['time'] - currentTime
                currentTime = n['time']
                onEvent = midi.NoteOnEvent(tick=dif,
                                           velocity=n['vel'],
                                           pitch=n['pitch'])
                track.append(onEvent)
                # Add note off to queue
                heapq.heappush(offs, (n['time'] + n['duration'], n['pitch']))
            # Insert leftover note off events from queue
            while offs:
                off = heapq.heappop(offs)
                dif = off[0] - currentTime
                currentTime = off[0]
                offEvent = midi.NoteOffEvent(tick=dif, pitch=off[1])
                track.append(offEvent)
            track.append(midi.EndOfTrackEvent(tick=1))
    midi.write_midifile(filepath, pattern)
예제 #25
0
def compose(pitchs, song_name, save_dir):
    start = 0
    song_length = 30
    # ticks = tracks[2][start:start+song_length]
    pitchs = pitchs[start:start + song_length]

    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)
    # start = ticks[0]
    for i in range(len(pitchs)):
        new_tick = 200
        # print(ticks[i], start, new_tick)
        # on = midi.NoteOnEvent(tick=new_tick, velocity=20, pitch=midi.C_6)
        # on = midi.NoteOnEvent(tick=new_tick, velocity=20, pitch=eval('midi.'+str(pitchs[i])))
        on = midi.NoteOnEvent(tick=new_tick, velocity=20, pitch=pitchs[i])
        track.append(on)
    # Add the end of track event, append it to the track
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)
    midi.write_midifile(song_name, pattern)
    return song_name
예제 #26
0
def notetomidi(notearray,i):
    note_len = 54

    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    
    last_note = 0
    for n in notearray:
        if n == 1 :
            note_len = note_len + 54
        elif int(n) > 1 :   
            track.append(midi.NoteOnEvent(tick=note_len, channel=0, data=[last_note, 0]))         
            track.append(midi.NoteOnEvent(tick=0, channel=0, data=[n, 110]))            
            last_note = n
            note_len = 54
    
    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    midi.write_midifile("example"+str(i)+".mid",pattern)
예제 #27
0
def encode_ir_to_midi(ir, filename, tempo=94):
    import midi
    # Instantiate a MIDI Pattern (contains a list of tracks)
    pattern = midi.Pattern()
    # Instantiate a MIDI Track (contains a list of MIDI events)
    track = midi.Track()
    # Append the track to the pattern
    pattern.append(track)

    tick = 0
    velocity = 70
    # 5.55 divisor is pretty accurate for CHORUS LINE MEDLEY and RHAPSODY IN BLUE.
    # Speed may vary during song -- perhaps Apple is slower when more
    # notes are played? CALL ME IRRESPONSIBLE is not quite as accurate,
    # nor is DO YOU THINK I'M SEXY (which is also corrupt).
    delay = tempo / 5.55  # 5.5 too slow, 5.75 too fast, 5.6 *slightly* too fast

    for inst in ir:
        op, val = inst
        if op == 'wait':
            # Default tempo (^) = 94
            # Other tempo (H) = 72
            # Tempo is actually just delay time, so is probably a straight division
            # Perhaps multiplier = tempo / 4 is a good start
            tick = int(round(
                val *
                delay))  # delay is about 15 for my stuff, about 25 for theirs
        elif op == 'on':
            track.append(
                midi.NoteOnEvent(tick=tick, velocity=velocity, pitch=val))
            tick = 0
        elif op == 'off':
            track.append(midi.NoteOffEvent(tick=tick, pitch=val))
            tick = 0

    track.append(midi.EndOfTrackEvent(tick=tick))

    # Save the pattern to disk
    midi.write_midifile(filename, pattern)
예제 #28
0
    def write_midi(self, midifile, resolution=1920, fillpitch=60):
        """
        Discards any tempo transition, assumes the tempo at the beginning of the measure
        stays the same for the entire measure

        midifile: path of the midi file
        resolution: the ticks per second
        fillpitch: the pitch to be used to fill each measure
        """
        import midi
        t = midi.Track()
        t.tick_relative = False
        sec2tick = lambda sec: int(sec * resolution)
        tempo = -1
        now = 0
        for i, measure in enumerate(self.measures):
            beat = self.index.measure2beat(i)
            assert (now - beat) < 0.0001, \
                "now: {}, beat: {}, timesig: {}, prev: {}".format(
                    now, beat, measure.timesig, self.measures[i - 1])
            temponow = int(self.tempocurve(beat))
            durbeats = measure.numbeats
            t.append(midi.TimeSignatureEvent(tick=sec2tick(now), 
                                             numerator=measure.num,
                                             denominator=measure.den))
            if temponow != tempo:
                tempo = temponow
                t.append(midi.SetTempoEvent(tick=sec2tick(now), bpm=tempo))
            t.append(midi.NoteOnEvent(tick=sec2tick(now),
                                      pitch=fillpitch, velocity=1))
            t.append(midi.NoteOffEvent(tick=sec2tick(now + durbeats), 
                                       pitch=fillpitch, velocity=0))
            now += durbeats
        t.append(midi.EndOfTrackEvent(tick=sec2tick(now) + 1))
        midipattern = midi.Pattern([t], resolution=resolution)
        midipattern.tick_relative = False
        midipattern.make_ticks_rel()
        midi.write_midifile(midifile, midipattern)
        return midipattern
예제 #29
0
파일: utils.py 프로젝트: harpone/DerpRNN
def noteStateMatrixToMidi(statematrix, name="example", lowerbound=21, upperbound=109):
    # code from: https://github.com/hexahedria/biaxial-rnn-music-composition/
    statematrix = np.asarray(statematrix)
    pattern = midi.Pattern()
    track = midi.Track()
    pattern.append(track)

    span = upperbound-lowerbound
    tickscale = 90

    lastcmdtime = 0
    prevstate = [[0,0] for x in range(span)]
    for time, state in enumerate(statematrix + [prevstate[:]]):
        offNotes = []
        onNotes = []
        for i in range(span):
            n = state[i]
            p = prevstate[i]
            if p[0] == 1:
                if n[0] == 0:
                    offNotes.append(i)
                elif n[1] == 1:
                    offNotes.append(i)
                    onNotes.append(i)
            elif n[0] == 1:
                onNotes.append(i)
        for note in offNotes:
            track.append(midi.NoteOffEvent(tick=(time-lastcmdtime)*tickscale, pitch=note+lowerbound))
            lastcmdtime = time
        for note in onNotes:
            track.append(midi.NoteOnEvent(tick=(time-lastcmdtime)*tickscale, velocity=40, pitch=note+lowerbound))
            lastcmdtime = time

        prevstate = state

    eot = midi.EndOfTrackEvent(tick=1)
    track.append(eot)

    midi.write_midifile("{}.mid".format(name), pattern)
예제 #30
0
def filter_ptrn_of_evnt_typs(old_ptrn, typs_2_keep=tuple(), f=copy.deepcopy):
    """
    Filter out unwanted event types from a midi.Pattern
    Returns a new midi.Pattern (not in-place) exclusively containing events 
    types contained in typs_2_keep. 
    """
    # It's necessary to convert ticks to abs. when removing
    # events otherwise timing issues occur
    old_ptrn.make_ticks_abs()
    new_ptrn = copy_ptrn(old_ptrn)
    for old_trck in old_ptrn:
        new_trck = midi.Track(tick_relative=False)  # old_trck.tick_relative
        for old_evnt in old_trck:
            if isinstance(old_evnt, typs_2_keep):
                new_evnt = f(old_evnt)
                new_trck.append(new_evnt)
        if len(new_trck):
            new_ptrn.append(new_trck)
    # We convert to rel. so that playback sounds correct
    old_ptrn.make_ticks_rel()
    new_ptrn.make_ticks_rel()
    return new_ptrn