예제 #1
0
    def choose_note(self, rn, last_two):
        """
        Choose the next note to output, given the current Roman Numeral and the last two notes played

        Args:
            rn (music21.roman.RomanNumeral): the current roman numeral
            last_two (int[]): array of last midi pitches played

        Returns:
            music21.pitch.Pitch: the next note to play
        """
        # find the appropriate counts matrix
        mat = self.counts[rn.scaleDegree - 1]

        # find the row in our matrix, and sum it.
        row = mat[tuple(last_two)]
        total = np.sum(row)

        # choose a random number between [0,total)
        rand = (random.randint(0, total - 1) if total > 0 else 0)

        i = 0
        rand -= row[i]

        # and select the corresponding row in the matrix
        while rand > 0:
            i += 1
            rand -= row[i]

        return music21.pitch.Pitch(midi2str(i))
예제 #2
0
    def choose_note(self,rn,last_two):
        """
        Choose the next note to output, given the current Roman Numeral and the last two notes played

        Args:
            rn (music21.roman.RomanNumeral): the current roman numeral
            last_two (int[]): array of last midi pitches played

        Returns:
            music21.pitch.Pitch: the next note to play
        """
        # find the appropriate counts matrix
        mat = self.counts[rn.scaleDegree-1]

        # find the row in our matrix, and sum it.
        row = mat[tuple(last_two)]
        total = np.sum(row)

        # choose a random number between [0,total)
        rand = (random.randint(0,total-1) if total > 0 else 0)

        i = 0
        rand -= row[i]

        # and select the corresponding row in the matrix
        while rand > 0:
            i += 1
            rand -= row[i]

        return music21.pitch.Pitch(midi2str(i))
예제 #3
0
    def get_notes(self,note_events, ppqn, track):
        """
        Given a list of note events (from function get_note_events), and ppqn (pulses per quarter note)
           returns list of note objects with appropriate durations and other properties

        Notes:
            this method calculates appropriate durations based on ppqn of track

        Args:
            note_events: the note events
            ppqn: pulses per quarter notes
            track (Track): the Track to analyze.

        Returns:
            Note[]: list of note objects with appropriate durations and other properties
        """
        note_objs = []
        unclosed_notes = defaultdict(lambda: [])  # holds running hash of notes that haven't seen an off event yet
                                                  # key is note pitch (integer from 0-127), value is a QUEUE of note_event tuples
        for note_event in note_events:
            on_off = note_event[0]
            tick = note_event[1]
            pitch = note_event[2]
            if on_off == 1:  # NoteOnEvent
                unclosed_notes[pitch].append(note_event)
            elif on_off == 0:  # NoteOffEvent
                if len(unclosed_notes[pitch]) == 0:
                    measure = note_event[1] / (ppqn * track.time_sig_bottom)
                    print 'Warning: <get_notes> NoteOffEvent without corresponding NoteOnEvent %r, measure: %r, instr: %r, pitch: %r ' % (str(note_event), str(measure), track.instr_name, str(pitch))
                else:
                    note_on = unclosed_notes[pitch].pop(0)
                    start_tick = note_on[1]
                    tick_dur = tick - start_tick

                    start = .25 * start_tick / ppqn  # 1 === whole note, .25 === quarter note
                    start = int(round(start * 32))  # final conversion to durk units: 1 === a 32nd note....32  === a whole note
                    dur = .25 * tick_dur / ppqn  # 1 === whole note, .25 === quarter note
                    dur = int(round(dur * 32))  # final conversion to durk units: 1 === a 32nd note....32  === a whole note

                    measure = start_tick / (ppqn * track.time_sig_bottom)

                    note_obj = Note(pitch=pitch, dur=dur, start=start, end=dur+start,
                                    tick_dur=tick_dur, start_tick=start_tick, measure=measure, track=track,
                                    iso_pitch=midi2str(pitch))
                    note_objs.append(note_obj)

            else:  # Error checking
                print 'Warning: <get_notes> Note is neither On nor Off event'

        return note_objs
예제 #4
0
import midi
from audiolazy import midi2str

from names import NoteOn, NoteOff, End

pattern = midi.read_midifile("twinkle-twinkle-little-star.mid")

for track in pattern:
    print("Next Track")
    for event in track:
        print("Next Event")
        if (event.name == NoteOn):
            pitch = event.get_pitch()
            # this is how loud the sound is, in the range (0, 127)
            # velocity = event.data[1]
            print("Note:", midi2str(pitch))
        elif (event.name == NoteOff):
            print("Silence")
        elif (event.name == End):
            print("End of Event")
        print("Length of time:", event.tick)
예제 #5
0
def midiToNoteStateMatrix(midifile, squash=True, span=span):
    pattern = midi.read_midifile(midifile)

    timeleft = [track[0].tick for track in pattern]

    posns = [0 for track in pattern]

    statematrix = []
    time = 0

    state = [[0, 0] for x in range(span)]
    statematrix.append(state)
    condition = True
    while condition:
        if time % (pattern.resolution / 4) == (pattern.resolution / 8):
            # Crossed a note boundary. Create a new state, defaulting to holding notes
            oldstate = state
            state = [[oldstate[x][0], 0] for x in range(span)]
            statematrix.append(state)
        for i in range(len(timeleft)):  #For each track
            if not condition:
                break
            while timeleft[i] == 0:
                track = pattern[i]
                pos = posns[i]
                evt = track[pos]
                #print (evt)
                if isinstance(evt, midi.NoteEvent):
                    if (evt.pitch < lowerBound) or (evt.pitch >= upperBound):
                        pass
                        # print "Note {} at time {} out of bounds (ignoring)".format(evt.pitch, time)
                    else:
                        #if evt.channel == 4 or evt.channel == 9:
                        print(audio.midi2str(evt.pitch))
                        print(evt.channel)
                        #player.note_on(evt.pitch)
                        if isinstance(evt,
                                      midi.NoteOffEvent) or evt.velocity == 0:
                            state[evt.pitch - lowerBound] = [0, 0]
                        #    player.note_off(evt.pitch)
                        else:
                            state[evt.pitch - lowerBound] = [1, 1]
                elif isinstance(evt, midi.TimeSignatureEvent):
                    if evt.numerator not in (2, 4):
                        # We don't want to worry about non-4 time signatures. Bail early!
                        # print "Found time signature event {}. Bailing!".format(evt)
                        out = statematrix
                        condition = False
                        break
                try:
                    timeleft[i] = track[pos + 1].tick
                    posns[i] += 1
                except IndexError:
                    timeleft[i] = None

            if timeleft[i] is not None:
                timeleft[i] -= 1

        if all(t is None for t in timeleft):
            break

        time += 1

    S = np.array(statematrix)
    statematrix = np.hstack((S[:, :, 0], S[:, :, 1]))
    statematrix = np.asarray(statematrix).tolist()
    return statematrix
    log = []
    for f in files:
        log.append(midi_to_excello(
            f, method, logging=True,
            printing=False))  # This also writes the file to disk.
    log.sort(key=lambda x: x[2], reverse=False)

    with open(midi_files.replace('/midi', '/csv') + '/' + 'log' + str(method) +
              '.txt',
              mode="w") as outfile:
        outfile.write('%s\n' % len(log))
        for s in log:
            outfile.write("%s\n" % s)


# In[694]:

for corpus in datasets:
    for method in [0, 1, 2]:
        print(corpus, method)
        convert_corpus(corpus, method)

# # MIDI note name conversion test

# In[655]:

import audiolazy
for i in range(12, 120):
    print(audiolazy.midi2str(i) == midi2str(i))