Exemplo n.º 1
0
 def to_midi(self, bar_offset, tpb):
     step = tpb // SCALE
     offset = bar_offset * 48
     return ct.Note(velocity=self.velocity,
                    pitch=self.pitch,
                    start=(self.position + offset) * step,
                    end=(self.position + self.duration + offset) * step)
Exemplo n.º 2
0
def play_chords(midi_obj):
    default_velocity = 63
    midi_maps = [
        chord_to_midi(Chord(marker.text)) for marker in midi_obj.markers
    ]
    new_midi_obj = parser.MidiFile()
    new_midi_obj.time_signature_changes.append(
        containers.TimeSignature(numerator=4, denominator=4, time=0))
    new_midi_obj.instruments.append(
        containers.Instrument(program=0, is_drum=False, name='Piano'))

    for midi_map, prev_marker, next_marker in zip(midi_maps,
                                                  midi_obj.markers[:-1],
                                                  midi_obj.markers[1:]):
        for midi_pitch in midi_map:
            midi_note = containers.Note(start=prev_marker.time,
                                        end=next_marker.time,
                                        pitch=midi_pitch,
                                        velocity=default_velocity)
            new_midi_obj.instruments[0].notes.append(midi_note)

    return new_midi_obj
Exemplo n.º 3
0
    def to_midi(self, output_path=None):
        midi = parser.MidiFile()

        midi.ticks_per_beat = DEFAULT_TICK_RESOL
        tempos = []
        chords = []
        instr_notes = defaultdict(list)

        time = 0
        for e in self.events:
            if isinstance(e, Bar):
                if e.tempo:
                    tempos += [ct.TempoChange(e.tempo, time)]
                if e.chord:
                    chords += [ct.Marker(e.chord, time)]
                time += DEFAULT_BAR_RESOL
            if isinstance(e, Note):
                s = DEFAULT_STEP * e.position + time
                instr_notes[e.inst_family] += [
                    ct.Note(e.velocity, e.pitch, s,
                            s + e.duration * DEFAULT_STEP)
                ]
        tempos.sort(key=lambda x: x.time)
        chords.sort(key=lambda x: x.time)

        instruments = []
        for k, v in instr_notes.items():
            inst = ct.Instrument(k * 8 if k < 16 else 0, k == 16)
            inst.notes = sorted(v, key=lambda x: x.start)
            instruments += [inst]

        midi.instruments = instruments
        midi.tempo_changes = tempos
        midi.key_signature_changes = []
        midi.time_signature_changes = []
        if output_path:
            midi.dump(output_path)
        return midi
Exemplo n.º 4
0
def pianoroll2notes(pianoroll, resample_factor=1.0):

    binarized = pianoroll > 0
    padded = np.pad(binarized, ((1, 1), (0, 0)), "constant")
    diff = np.diff(padded.astype(np.int8), axis=0)

    positives = np.nonzero((diff > 0).T)
    pitches = positives[0]
    note_ons = positives[1]
    note_offs = np.nonzero((diff < 0).T)[1]

    notes = []
    for idx, pitch in enumerate(pitches):
        st = note_ons[idx]
        ed = note_offs[idx]
        velocity = pianoroll[st, pitch]
        velocity = max(0, min(127, velocity))
        notes.append(
            ct.Note(velocity=int(velocity),
                    pitch=pitch,
                    start=int(st * resample_factor),
                    end=int(ed * resample_factor)))
    notes.sort(key=lambda x: x.start)
    return notes
Exemplo n.º 5
0
# create an  instrument
track = ct.Instrument(program=0, is_drum=False, name='example track')
mido_obj.instruments = [track]

# create eighth notes
duration = int(beat_resol * 0.5)
prev_end = 0
pitch = 60
print(' > create a dummy file')
for i in range(10):
    # create one note
    start = prev_end
    end = prev_end + duration
    pitch = pitch
    velocity = np.random.randint(1, 127)
    note = ct.Note(start=start, end=end, pitch=pitch, velocity=velocity)
    print(i, note)
    mido_obj.instruments[0].notes.append(note)

    # prepare next
    prev_end = end
    pitch += 1

# save (with BytesIO)
memory = BytesIO()
mido_obj.dump(file=memory)

# -------------------------------------- #
#  Test Bytes IO                         #
# -------------------------------------- #
print(' === reload ===')
Exemplo n.º 6
0
def gen_midi(note_seq, out_file):
    #Check Seq
    seq = []
    current_is_pitch = 'PITCH'

    #遍历寻找pitch-duration的结构
    #当有不合法情况出现时,找最后一个pitch和第一个duration,保证其相邻
    #p1 d1 p2 p3 d2 p4 d3-> p1 d1 p3 d1 p4 d3
    #p1 d1 p2 d2 d3 p3 d4-> p1 d1 p2 d2 p3 d4
    #p1 d1 p2 p3 d2 d3 p4 d4 -> p1 d1 p3 d2 p4 d4

    i = 0
    while (i < len(note_seq)):
        if note_seq[i] > 128:
            #Duration
            i += 1
            continue
        else:
            #Pitch
            if i + 1 >= len(note_seq):
                #No Duration Followed
                break
            if note_seq[i + 1] <= 128:
                #Followed by a pitch
                i += 1
                continue

            #Followed by a duration
            pitch = note_seq[i]
            duration = float(Duration_vocab[note_seq[i + 1]])
            seq.append((pitch, duration))
            i += 2

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

    # create an empty file
    mido_obj = mid_parser.MidiFile()
    beat_resol = mido_obj.ticks_per_beat

    # create an  instrument
    track = ct.Instrument(program=0, is_drum=False, name='Lead')
    mido_obj.instruments = [track]

    prev_end = 0
    # rest_time = 0

    for note in seq:
        print(note)
        duration = round(note[1] * beat_resol)
        if note[0] < 128:  # Pitch
            start = prev_end
            end = prev_end + duration
            print(f"{note[0]} from {start} to {end}")
            nt = ct.Note(start=start, end=end, pitch=note[0], velocity=100)
            mido_obj.instruments[0].notes.append(nt)
            prev_end += duration

            # Instantiate a MIDI note on event, append it to the track
            # tick:according to last?
            # on = midi.NoteOnEvent(tick=rest_time, velocity=100, pitch=note[0])
            # track.append(on)

            # # Instantiate a MIDI note off event, append it to the track
            # off = midi.NoteOffEvent(tick=round(note[1]*mspb), pitch=note[0])
            # track.append(off)

            # rest_time = 0
        else:  # Rest
            assert note[0] == REST_NOTE
            prev_end += duration
            # rest_time += round(note[1]*mspb)

    # create makers
    marker_hi = ct.Marker(time=0, text='HI')
    mido_obj.markers.append(marker_hi)

    mido_obj.tempo_changes.append(ct.TempoChange(240, 0))

    mido_obj.dump(out_file)