Example #1
0
    def note_with_rhythm_pattern(self, rhythm, c=['C5', 'D5']):
        '''
        A music clip note with rhythm
        '''
        t = 0
        c_len = len(c)

        for r in rhythm:

            note_number = pretty_midi.note_name_to_number(c[t])

            note = pretty_midi.Note(
                velocity=20, pitch=note_number, start=r[0], end=r[1])
            self.pm.instruments[0].notes.append(note)
            note_number = pretty_midi.note_name_to_number(c[t + 1])

            note = pretty_midi.Note(
                velocity=30, pitch=note_number, start=r[0], end=r[1])
            self.pm.instruments[0].notes.append(note)
            note_number = pretty_midi.note_name_to_number(c[t + 2])
            note = pretty_midi.Note(
                velocity=20, pitch=note_number, start=r[0], end=r[1])
            self.pm.instruments[0].notes.append(note)

            if (t + 6) >= c_len:
                break
            t += 3
def make_song(file,instr=0):
    res = 960
    tempo = 120
    pm = pretty_midi.PrettyMIDI(resolution=res, initial_tempo=tempo) #pretty_midiオブジェクトを作ります
    instrument = pretty_midi.Instrument(instr) #instrumentはトラックに相当します。
    
    note = pretty_midi.Note(velocity=100, pitch=60, start=0, end=0.25)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=62, start=0.25, end=0.5)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=64, start=0.5, end=0.75)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=65, start=0.75, end=1)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=67, start=1, end=1.5)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=69, start=1.5, end=1.75)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=65, start=1.75, end=2)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=64, start=2, end=2.25)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=62, start=2.5, end=2.75)
    instrument.notes.append(note)
    note = pretty_midi.Note(velocity=100, pitch=60, start=3, end=4)
    instrument.notes.append(note)
    
    pm.instruments.append(instrument)
    pm.write(file) #midiファイルを書き込みます。
Example #3
0
def rando_midi(filename):
    # Create a PrettyMIDI object
    cello_c_chord = pretty_midi.PrettyMIDI()
    # Create an Instrument instance for a cello instrument
    cello_program = pretty_midi.instrument_name_to_program('Cello')
    cello = pretty_midi.Instrument(program=cello_program)
    # Iterate over note names, which will be converted to note number later
    for note_name in ['F4', 'A5', 'C5']:
        # Retrieve the MIDI note number for this note name
        note_number = pretty_midi.note_name_to_number(note_name)
        # Create a Note instance for this note, starting at 0s and ending at .5s
        note = pretty_midi.Note(velocity=100, pitch=note_number, start=0, end=2)        
        # Add it to our cello instrument
        cello.notes.append(note)
    for note_name in ['C5', 'E5', 'G5']:
        # Retrieve the MIDI note number for this note name
        note_number = pretty_midi.note_name_to_number(note_name)
        # Create a Note instance for this note, starting at 0s and ending at .5s
        note = pretty_midi.Note(velocity=100, pitch=note_number, start=2, end=4)
        # Add it to our cello instrument
        cello.notes.append(note)
    # Add the cello instrument to the PrettyMIDI object
    cello_c_chord.instruments.append(cello)

    # Write out the MIDI data
    cello_c_chord.write(filename)
Example #4
0
    def test_merge_midi(self):
        egp_chord = pretty_midi.PrettyMIDI()
        # egp_program = pretty_midi.instrument_name_to_program('Lead 2 (sawtooth)')
        egp_program = pretty_midi.instrument_name_to_program('Synth Bass 1')
        egp = pretty_midi.Instrument(program=egp_program)

        midi_data = pretty_midi.PrettyMIDI('180827_01_midi.mid')
        midi_data2 = pretty_midi.PrettyMIDI('180827_02_midi.mid')

        adding = midi_data.get_end_time()

        for instrument in midi_data.instruments:
            if not instrument.is_drum:
                for note in instrument.notes:
                    # print(note.pitch, note.velocity, note.start, note.end)
                    note = pretty_midi.Note(velocity=note.velocity,
                                            pitch=note.pitch,
                                            start=note.start,
                                            end=note.end)
                    egp.notes.append(note)

        for instrument in midi_data2.instruments:
            if not instrument.is_drum:
                for note in instrument.notes:
                    # print(note.pitch, note.velocity, note.start, note.end)
                    note = pretty_midi.Note(velocity=note.velocity,
                                            pitch=note.pitch,
                                            start=note.start + adding,
                                            end=note.end + adding)
                    egp.notes.append(note)

        egp_chord.instruments.append(egp)
        egp_chord.write('SynthBass1.mid')
Example #5
0
def GVmidi(df, submidi, stdmidi, sub_name, std_name):
    new_out = df.iloc[:,4:8]

    new_notes1 = []
    for row in new_out.iterrows():
        new_notes1.append(pretty_midi.Note(
            velocity=int(row[1][3]), pitch=int(row[1][0]), start=row[1][1], end=row[1][2]))
    submidi.instruments[0].notes = new_notes1

    new_notes2 = []
    std_df = new_out = df.iloc[:,:4]
    for row in std_df.iterrows():
        new_notes2.append(pretty_midi.Note(
            velocity=int(row[1][3]), pitch=int(row[1][0]), start=row[1][1], end=row[1][2]))
    stdmidi.instruments[0].notes = new_notes2

    submidi.write(sub_name + '-m.midi')
    stdmidi.write(std_name + '-m.midi')

    loaded1 = Multitrack(sub_name + '-m.midi')
    loaded2 = Multitrack(std_name + '-m.midi')
    fig1, axs1 = loaded1.plot()
    fig2, axs2 = loaded2.plot()
    axs1[0].set_title('sub_mini')
    axs2[0].set_title('std_midi')
    # plt.show()
    fig1.savefig(sub_name + '.jpg')
    fig2.savefig(std_name + '.jpg')

    return new_notes1
Example #6
0
def chord_to_instrument(chord_array, frame_per_bar=16):
    frame_per_second = (frame_per_bar / 4) * 2
    unit_time = 1 / frame_per_second
    instrument = pretty_midi.Instrument(program=0, name='chord')
    chord = chord_array[0]
    prev_t = 0
    for t in range(chord_array.shape[0]):
        if not (chord_array[t] == chord).all():
            chord_notes = chord.nonzero()[0]
            for pitch in chord_notes:
                note = pretty_midi.Note(start=prev_t * unit_time,
                                        end=t * unit_time,
                                        pitch=48 + pitch,
                                        velocity=70)
                instrument.notes.append(note)
            prev_t = t
            chord = chord_array[t]
    chord_notes = chord.nonzero()[0]
    for pitch in chord_notes:
        note = pretty_midi.Note(start=prev_t * unit_time,
                                end=chord_array.shape[0] * unit_time,
                                pitch=48 + pitch,
                                velocity=70)
        instrument.notes.append(note)
    return instrument
Example #7
0
def run():

    path = tkinter.filedialog.askopenfilename(
        title="Select file", 
        filetypes=(("midi files", "*.mid"), ("all files", "*.*")))

    insert_text('IN - ' + path)

    midi_data = pretty_midi.PrettyMIDI(path)
    for instrument in midi_data.instruments:
        if instrument.is_drum:
            continue

        temp_note = []
        for note in instrument.notes:
            for pit in range(note.pitch-12, -1, -12):
                temp = pretty_midi.Note(velocity=note.velocity, pitch=pit, start=note.start, end=note.end)
                temp_note.append(temp)

            for pit in range(note.pitch+12, 128, 12):
                temp = pretty_midi.Note(velocity=note.velocity, pitch=pit, start=note.start, end=note.end)
                temp_note.append(temp)
        instrument.notes = instrument.notes + temp_note
    
    path = tkinter.filedialog.asksaveasfilename(
        title="Select file", 
        filetypes=(("midi files", "*.mid"), ("all files", "*.*")))

    midi_data.write(path)
    insert_text('OUT - ' + path)
    insert_text('Complete')
Example #8
0
def resample():
    chord, pr_mat, midi_in_path = get_select_sample()

    in_midi_notes = pretty_midi.PrettyMIDI(midi_in_path).instruments[0].notes

    out_midi = pretty_midi.PrettyMIDI()
    out_midi.instruments = [pretty_midi.Instrument(0)]
    for note in in_midi_notes:
        out_midi.instruments[0].notes.append(
            pretty_midi.Note(note.velocity, note.pitch, note.start * 4 / 3,
                             min([note.end * 4 / 3, SAMPLE_LEN])))

    for i in range(SAMPLE_LEN):
        out_midi.instruments[0].notes.append(pretty_midi.Note(1, 30, i, i + 1))

    midi_path = 'static/uploads/{}.mid'.format(
        str(datetime.datetime.today()).replace("-",
                                               "").replace(" ", "").replace(
                                                   ":", "").replace(".", ""))
    np.savez(midi_path[:-3] + 'npz', pr_mat=pr_mat, chord=chord)
    out_midi.write(midi_path)
    return {
        "midi": midi_path,
        "chords": chd_to_str(chord),
        "chd_mat": chord.tolist()
    }
Example #9
0
def matrixToMidi(matrix, dest_file, onehot=True):
    # Create a PrettyMIDI object
    midi_obj = pretty_midi.PrettyMIDI()
    # Create an Instrument instance for a Piano instrument
    piano_program = pretty_midi.instrument_name_to_program(
        'Acoustic Grand Piano')
    piano = pretty_midi.Instrument(program=piano_program)
    n_notes = matrix.shape[0]
    t = 0.0
    if (onehot):
        note_matrix = [np.where(r == 1)[0][0] for r in matrix[:, 0:128]]
        print(note_matrix)
        for i in range(0, n_notes):
            p = note_matrix[i]
            s = t  # Start = current time
            e = s + matrix[i, 128]  #End = start + duration of note in seconds
            note = pretty_midi.Note(velocity=100, pitch=p, start=s, end=e)
            piano.notes.append(note)
            t = e
            #print(s)
    else:
        for i in range(0, n_notes):
            p = int(matrix[i, 0])
            s = matrix[i, 2] + t  # Start = rest before note + current time
            e = s + matrix[i, 1]  # End = start + duration of note in seconds
            note = pretty_midi.Note(velocity=100, pitch=p, start=s, end=e)
            #print("pitch: %d start: %f , end: %f" % (p,s,e))
            piano.notes.append(note)
            t = e

    midi_obj.instruments.append(piano)
    midi_obj.write(dest_file)
Example #10
0
def chords(notes=None, root=None):
    import pretty_midi
    import numpy.random as rnd
    import os

    # sanitize some; root is MIDI integer, chord are relative notes to add.
    chord = tuple(map(int, notes.split(',')))[:16]
    root = int(root)

    pm = pretty_midi.PrettyMIDI(initial_tempo=80)
    inst = pretty_midi.Instrument(program=24, is_drum=False, name='')
    pm.instruments.append(inst)

    # root note,
    inst.notes.append(pretty_midi.Note(88, root, 0, 0.5))
    # and chord components:
    for note in chord:
        inst.notes.append(pretty_midi.Note(88, root + note, 0, 0.8))

    hF = '/tmp/gabor-{:x}'.format(rnd.randint(1000, 99999999))

    pm.write('{}.mid'.format(hF))
    os.system(
        'timidity {0}.mid --output-mono -Ow -o - | ffmpeg -i - {0}.mp3'.format(
            hF))
    os.unlink('{}.mid'.format(hF))
    o = send_file('{}.mp3'.format(hF))
    os.unlink('{}.mp3'.format(hF))

    return o
Example #11
0
def first_sampleC():
    chord, pr_mat, midi_in_path = get_select_sample()

    in_midi_notes = pretty_midi.PrettyMIDI(midi_in_path).instruments[0].notes

    out_midi = pretty_midi.PrettyMIDI()
    out_midi.instruments = [pretty_midi.Instrument(0)]
    for note in in_midi_notes:
        out_midi.instruments[0].notes.append(
            pretty_midi.Note(note.velocity, note.pitch, note.start * 4 / 3,
                             min([note.end * 4 / 3, SAMPLE_LEN])))

    for i in range(SAMPLE_LEN):
        out_midi.instruments[0].notes.append(pretty_midi.Note(1, 30, i, i + 1))

    midi_path = 'static/uploads/{}.mid'.format(
        str(datetime.datetime.today()).replace("-",
                                               "").replace(" ", "").replace(
                                                   ":", "").replace(".", ""))
    np.savez(midi_path[:-3] + 'npz', pr_mat=pr_mat, chord=chord)
    out_midi.write(midi_path)

    send = {}
    send['midi_path'] = midi_path[7:]
    send['chords'] = chd_to_str(chord)
    send['chd_mat'] = chord.tolist()
    send['SAMPLE_LEN'] = SAMPLE_LEN
    send['CHORD_LEN_QUANT'] = CHORD_LEN_QUANT
    return render_template('indexC.html', send=send)
Example #12
0
def generate_midi_segment_from_tensor(data, path):
    pm = pretty_midi.PrettyMIDI()
    instr_track = pretty_midi.Instrument(program=0, is_drum=False, name='Instr')
    quarter_length = 60 / 120 / 4
    note_range = 84
    time_step = 64

    for note in range(note_range):
        during_note = False
        note_begin = 0
        for time in range(time_step):
            has_note = data[time, note] >= 0.5

            if has_note:
                if not during_note:
                    during_note = True
                    note_begin = time * quarter_length
                else:
                    if time != time_step-1:
                        continue
                    else:
                        note_end = time * quarter_length
                        instr_track.notes.append(pretty_midi.Note(127, note + 24, note_begin, note_end))
                        during_note = False
            else:
                if not during_note:
                    continue
                else:
                    note_end = time * quarter_length
                    instr_track.notes.append(pretty_midi.Note(127, note + 24, note_begin, note_end))
                    during_note = False
    pm.instruments.append(instr_track)
    pm.write(path)
Example #13
0
def chords2midi(chords_dict, file_name):
    # pretty midiオブジェクトを作る
    piano_chord = pretty_midi.PrettyMIDI()

    # 楽器名を入れると、対応するgeneral midi program numberを返す
    piano_program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano')

    # Instrument instanceをcelloとして作成
    piano = pretty_midi.Instrument(program=piano_program)

    # 解析したコードを単音のリストにバラす
    for i, chord in enumerate(chords_dict["chords_result"]["chords"]):
        logger.info(i, chord)
        # Nの時はスキップ(ノートに書き込まない)
        if chord['chord'] == "N":
            continue
        chords_list = key2chord(chord)
        logger.info("chords list: {}".format(chords_list))
        logger.info("start time: {}".format(chord["time"]))
        logger.info("end time: {}".format(chords_dict["chords_result"]["chords"][i+1]["time"]-0.1))
        # print("time: {}".format(float(chords_dict["chords_result"]["chords"][i+1]["time"])-float(chord["time"])))
        for note_name in chords_list:
            # コードの名前を数字に変換
            note_number = pretty_midi.note_name_to_number(note_name)
            logger.info("chord name {0}, chord num {1}".format(note_name, note_number))
            # velocityを定義する
            try:
                note = pretty_midi.Note(
                    velocity=100,
                    pitch=note_number,
                    start=chord["time"],
                    end=chords_dict["chords_result"]
                            ["chords"][i+1]["time"]-0.1
                )
                # print(note)
                # 上記で作成したnoteをchelloインスタンスに加える
                piano.notes.append(note)
            except IndexError:  # 最後の章は0.5秒とする
                logger.info("note last code")
                note = pretty_midi.Note(
                    velocity=100,
                    pitch=note_number,
                    start=chord["time"],
                    end=chord["time"]+0.5
                )
                # 上記で作成したnoteをchelloインスタンスに加える
                piano.notes.append(note)
    # PrettyMIDIオブジェクトに加える
    piano_chord.instruments.append(piano)
    print(piano)
    print(piano_chord)
    midi_file = "midi/" + str(file_name) + ".mid"
    # MIDIファイルとして書き出す
    piano_chord.write(midi_file)

    # Load MIDI file into PrettyMIDI object
    midi_data = pretty_midi.PrettyMIDI(midi_file)
    # Print an empirical estimate of its global tempo
    print(midi_data.estimate_tempo())
Example #14
0
def build_midi_from_tensor(src_path,
                           save_path,
                           time_step=120,
                           bar_length=4,
                           valid_range=(24, 108)):
    data = build_single_tensor_from_sparse(src_path)
    piece_num = data.shape[0]
    instr_list = ['Drums', 'Piano', 'Guitar', 'Bass', 'Strings']
    program_list = [0, 0, 24, 32, 48]
    pm = pretty_midi.PrettyMIDI()
    for i in range(5):
        instr = instr_list[i]
        is_drum = (instr == 'Drums')
        instr_track = pretty_midi.Instrument(program_list[i],
                                             is_drum=is_drum,
                                             name=instr)
        track_data = data[:, :, :, :, i]

        for piece in range(piece_num):
            for bar in range(bar_length):
                init_time = piece * (bar_length * time_step) + bar * time_step
                print(init_time)
                for note in range(valid_range[1] - valid_range[0]):

                    during_note = False
                    note_begin = init_time

                    for time in range(time_step):
                        has_note = track_data[piece, bar, time, note]
                        if has_note:
                            if not during_note:
                                during_note = True
                                note_begin = time + init_time
                            else:
                                if time != time_step - 1:
                                    continue
                                else:
                                    note_end = time + init_time
                                    print(note_begin / 60, note_end / 60)
                                    instr_track.notes.append(
                                        pretty_midi.Note(
                                            64, note + 12, note_begin / 48,
                                            note_end / 48))
                        else:
                            if not during_note:
                                continue
                            else:
                                note_end = time + init_time
                                print(note_begin / 60, note_end / 60)
                                instr_track.notes.append(
                                    pretty_midi.Note(64, note + 12,
                                                     note_begin / 48,
                                                     note_end / 48))
                                during_note = False

        pm.instruments.append(instr_track)

    pm.write(save_path)
Example #15
0
def create_midi_from_piece(piece: Piece,
                           midi_path: str,
                           measure_in_seconds: float,
                           instruments: List[int],
                           velocity: int,
                           opening_silence_in_seconds: float = 1.0,
                           trailing_silence_in_seconds: float = 1.0) -> None:
    """
    Create MIDI file from a piece created by this package.

    :param piece:
        musical piece
    :param midi_path:
        path where resulting MIDI file is going to be saved
    :param measure_in_seconds:
        duration of one measure in seconds
    :param instruments:
        IDs of instruments (according to General MIDI specification)
        that play corresponding melodic lines
    :param velocity:
        one common velocity for all notes
    :param opening_silence_in_seconds:
        number of seconds with silence to add at the start of the composition
    :param trailing_silence_in_seconds:
        number of seconds with silence to add at the end of the composition
    :return:
        None
    """
    numeration_shift = pretty_midi.note_name_to_number('A0')
    pretty_midi_instruments = []
    for melodic_line, instrument in zip(piece.melodic_lines, instruments):
        pretty_midi_instrument = pretty_midi.Instrument(program=instrument)
        for element in melodic_line:
            start_time = element.start_time * measure_in_seconds
            start_time += opening_silence_in_seconds
            end_time = start_time + element.duration * measure_in_seconds
            pitch = element.position_in_semitones + numeration_shift
            note = pretty_midi.Note(start=start_time,
                                    end=end_time,
                                    pitch=pitch,
                                    velocity=velocity)
            pretty_midi_instrument.notes.append(note)
        pretty_midi_instrument.notes.sort(key=lambda x: (x.start, x.pitch))
        pretty_midi_instruments.append(pretty_midi_instrument)

    trailing_silence_start = piece.n_measures * measure_in_seconds
    trailing_silence_start += opening_silence_in_seconds
    note = pretty_midi.Note(
        velocity=0,
        pitch=1,  # Arbitrary value that affects nothing.
        start=trailing_silence_start,
        end=trailing_silence_start + trailing_silence_in_seconds)
    pretty_midi_instruments[0].notes.append(note)

    composition = pretty_midi.PrettyMIDI()
    for pretty_midi_instrument in pretty_midi_instruments:
        composition.instruments.append(pretty_midi_instrument)
    composition.write(midi_path)
Example #16
0
    def crop_by_measure(self):
        cropped_pm = []

        for measure in range(self.measures_num):
            pm = pretty_midi.PrettyMIDI()
            piano = pretty_midi.Instrument(program=0)

            for instr in self.pm.instruments:
                for note in instr.notes:
                    pitch = note.pitch
                    velocity = note.velocity

                    start_time, end_time = note.start, note.end
                    start_measure, end_measure = int(start_time // 2), int(
                        end_time // 2)

                    if start_measure > measure or end_measure < measure:
                        continue

                    else:
                        if start_measure == end_measure == measure:
                            new_start, new_end = start_time - measure * 2.0, end_time - measure * 2.0
                            new_note = pretty_midi.Note(velocity=velocity,
                                                        pitch=pitch,
                                                        start=new_start,
                                                        end=new_end)
                            piano.notes.append(new_note)

                        elif start_measure == measure < end_measure:
                            new_start, new_end = start_time - measure * 2.0, 2.0
                            new_note = pretty_midi.Note(velocity=velocity,
                                                        pitch=pitch,
                                                        start=new_start,
                                                        end=new_end)
                            piano.notes.append(new_note)

                        elif start_measure < measure == measure:
                            new_start, new_end = 0, end_time - measure * 2.0
                            new_note = pretty_midi.Note(velocity=velocity,
                                                        pitch=pitch,
                                                        start=new_start,
                                                        end=new_end)
                            piano.notes.append(new_note)

                        else:
                            assert start_measure < measure < end_measure
                            new_start, new_end = 0, 2.0
                            new_note = pretty_midi.Note(velocity=velocity,
                                                        pitch=pitch,
                                                        start=new_start,
                                                        end=new_end)
                            piano.notes.append(new_note)

            pm.instruments.append(piano)
            cropped_pm.append(pm)

        return cropped_pm
Example #17
0
    def skyline_for_instrument(self, instrument):
        ''' Apply skyline algorithm to an instrument.

        Arg:
        - instrument: A `pretty_midi.Instrument` object.

        Return:
        - skyline_instrument: A `pretty_midi.Instrument` object with melody
        extracted by skyline algorithm.
        '''

        skyline_instrument = copy.deepcopy(instrument)
        notes = skyline_instrument.notes
        n_notes = len(notes)  # number of notes

        # when the length is too short, don't process it
        if n_notes < 2:
            return skyline_instrument

        # make sure all the notes are sorted by start time
        notes.sort(key=lambda note: note.start)

        # start skyline algorithm
        k = j = 0

        while j < n_notes - 1:
            k = j + 1

            # handle the situation where note_j and note_k have a same pitch
            while (k <= n_notes - 1) and (notes[j].start == notes[k].start):
                if notes[j].pitch < notes[k].pitch:
                    # label note_j's start point -1 for later process
                    notes[j] = pretty_midi.Note(
                        notes[j].velocity, notes[j].pitch, -1, notes[j].end)
                    j = k
                    k += 1
                else:
                    # label note_k's start point -1 for later process
                    notes[k] = pretty_midi.Note(
                        notes[k].velocity, notes[k].pitch, -1, notes[k].end)
                    k += 1

            if k > n_notes - 1:
                break

            # handle the situation where note_j comes before note_k
            if notes[j].end > notes[k].start:
                notes[j] = pretty_midi.Note(notes[j].velocity, notes[j].pitch,
                                            notes[j].start, notes[k].start)

            j = k

        # eliminate all the notes whose start points are -1
        notes = [note for note in notes if note.start != -1]
        skyline_instrument.notes = notes

        return skyline_instrument
Example #18
0
def make_midi(dict_note, pred_argmax, x_num, y_num, TEMPO, NUMERATOR,
              DENOMINATOR, path_output_melody_chords_midi):
    def calc_notetime(tempo, numerator, denominator):
        notetime = [0] * 10
        j = 64
        for i in range(9):
            notetime[i + 1] = 60 * numerator * (1 / j) / tempo
            j /= 2
        return notetime

    # 音を鳴らす間隔(nt[5]は4分音符)
    nt = calc_notetime(TEMPO, NUMERATOR, DENOMINATOR)

    pm = pretty_midi.PrettyMIDI(resolution=960, initial_tempo=TEMPO)
    instrument = pretty_midi.Instrument(
        program=89, is_drum=False)  # 89:synth pad(fantasia)

    # melody
    time = 0
    for i in range(x_num):
        for j in range(y_num):
            note_name = dict_note[str(i) + str(j)][0]
            note_number = pretty_midi.note_name_to_number(note_name)
            d_time = nt[int(math.log2(64 * dict_note[str(i) + str(j)][1]))]
            # if dict_note[str(i)+str(j)][1] =0.5,
            # d_time = nt[5]

            note = pretty_midi.Note(velocity=100,
                                    pitch=note_number,
                                    start=time,
                                    end=time + d_time)
            instrument.notes.append(note)
            time = time + d_time

    # chords
    time = 0
    for chord_num in pred_argmax[0]:
        note_names = chords_li[chord_num]

        d_time = nt[7]  # 全音符

        for note_name in note_names:
            note_number = pretty_midi.note_name_to_number(note_name)
            note = pretty_midi.Note(velocity=100,
                                    pitch=note_number,
                                    start=time,
                                    end=time + d_time)
            instrument.notes.append(note)

        time = time + d_time

    pm.instruments.append(instrument)
    pm.write(path_output_melody_chords_midi)

    print('')
    print('FInish generating MIDI file (melody+chord) .')
Example #19
0
 def test_two_notes_plot(self):
     plotter = Plotter()
     pretty_midi = pm.PrettyMIDI()
     pretty_midi.instruments.append(pm.Instrument(0))
     notes = [pm.Note(100, 36, 1.5, 1.7),
              pm.Note(100, 37, 3.5, 4.0)]
     [pretty_midi.instruments[0].notes.append(note) for note in notes]
     plotter.plot(pretty_midi)
     output_file = os.path.join("output", "test_two_notes_plot.html")
     plotter.save(pretty_midi, output_file)
Example #20
0
def inference(pred, beat_th=0.5, down_beat_th=0.5, min_dist=0.3, t_unit=0.1):
    """Infers the beat and down beat positions from the raw prediction values.

    Parameters
    ----------
    pred: 2D numpy array
        The prediction of the model.
    beat_th: float
        Threshold for beat channel.
    down_beat_th: float
        Threshold for down beat channel.
    min_dist: float
        Minimum distance between two beat positions in seconds.
    t_unit: float
        Time unit of each frame in seconds.

    Returns
    -------
    midi: pretty_midi.PrettyMIDI
        Inferred beat positions recorded as MIDI notes. Information of beat
        and down beat are recorded in two different instrument tracks.
    """
    mdist = max(1, round(min_dist / t_unit))
    beat_pos, _ = find_peaks(pred[:, 0], height=beat_th, distance=mdist)
    db_pos, _ = find_peaks(pred[:, 1], height=down_beat_th, distance=mdist)

    beat_notes = []
    for pos in beat_pos:
        start_time = pos * t_unit
        end_time = start_time + 0.5
        beat_notes.append(
            pretty_midi.Note(start=start_time,
                             end=end_time,
                             pitch=BEAT_NOTE_NUM,
                             velocity=100))

    db_notes = []
    for pos in db_pos:
        start_time = pos * t_unit
        end_time = start_time + 0.5
        db_notes.append(
            pretty_midi.Note(start=start_time,
                             end=end_time,
                             pitch=DOWN_BEAT_NOTE_NUM,
                             velocity=100))

    beat_inst = pretty_midi.Instrument(is_drum=True, program=0, name="Beat")
    beat_inst.notes += beat_notes
    db_inst = pretty_midi.Instrument(is_drum=True, program=0, name="Down Beat")
    db_inst.notes += db_notes

    midi = pretty_midi.PrettyMIDI()
    midi.instruments = [beat_inst, db_inst]
    return midi
Example #21
0
def seq2piano(seq):
    '''
    Convert a sequence of events to midi
    :param seq: numpy array that contains the sequence
    :return: midi object
    '''
    midi = pretty_midi.PrettyMIDI()
    piano = pretty_midi.Instrument(program=0, is_drum=False, name='piano')
    midi.instruments.append(piano)

    if seq.ndim > 1:
        seq = np.argmax(seq, axis=-1)
    inote = {}
    velo = 40
    time = 0.
    for e in seq:
        t, v = Event.decode(e)
        if t == 'shift':
            time += v
        elif t == 'velo':
            velo = v
            for n in inote.values():
                if n[2] == time:
                    n[0] = v
        elif t == 'down':
            n = inote.get(v, None)
            if n is not None:
                logging.debug(
                    'consecutive downs for pitch %d at time %d and %d' %
                    (v, n[2], time))
            else:
                inote[v] = [velo, v, time, -1]
        else:
            n = inote.get(v, None)
            if n is not None:
                n[-1] = time
                if n[-1] > n[-2]:
                    piano.notes.append(pretty_midi.Note(*n))
                else:
                    logging.debug(
                        'note with non-positive duration for pitch %d at time %d'
                        % (n[1], n[2]))
                del inote[v]
            else:
                logging.debug('up without down for pitch %d at time %d' %
                              (v, time))

    # clean out the incomplete note buffer, assuming these note end at last
    for n in inote.values():
        n[-1] = time
        if n[-1] > n[-2]:
            piano.notes.append(pretty_midi.Note(*n))

    return midi
Example #22
0
    def music_generation(self,input_values,actual_values,duration,velocity_values,start_time, file_name):
        '''
        

        Parameters:
            - input_values (list) : 
            - actual_values (torch.Tensor) :
            - duration (torch.Tensor) :
            - velocity_values (list) :
            - start_time (list):
            - file_name (string):

        Returns:
            - None

        '''


        final_list=[]
        final_end_time_list=[]
        counter=0
        #print(len(actual_values))
        
        for i in range(len(input_values)):
            if(i==0):
                note=pretty_midi.Note(pitch=int(input_values[i]),velocity=int(velocity_values[i]),start=start_time[i],end=start_time[i]+duration[i])
                self.cello.notes.append(note)
                final_list.append(note)
                note=pretty_midi.Note(pitch=int(actual_values[counter]),velocity=int(velocity_values[i]),start=start_time[i],end=start_time[i]+duration[i])
                final_end_time_list.append(start_time[i]+duration[i])
                self.cello.notes.append(note)
                final_list.append(note)
            else:
                if((start_time[i]-final_end_time_list[counter])>=0):
                    
                    counter+=1
                    note=pretty_midi.Note(pitch=int(input_values[i]),velocity=int(velocity_values[i]),start=start_time[i],end=start_time[i]+duration[i])
                    self.cello.notes.append(note)
                    final_list.append(note)
                    note=pretty_midi.Note(pitch=int(actual_values[counter]),velocity=int(velocity_values[i]),start=start_time[i],end=start_time[i]+duration[i])
                    self.cello.notes.append(note)
                    final_list.append(note)
                    final_end_time_list.append(start_time[i]+duration[i])
                else:
                    note=pretty_midi.Note(pitch=int(input_values[i]),velocity=int(velocity_values[i]),start=start_time[i],end=start_time[i]+duration[i])
                    self.cello.notes.append(note)
                    final_list.append(note)
        self.cello_c_chord.instruments.append(self.cello)
   
        # Write out the MIDI data
        # print(counter)
        print(final_list)

        self.cello_c_chord.write('output/{}.mid'.format(file_name))
Example #23
0
def create_notes(velocity=100):
    notes = []
    notes.append(
        pretty_midi.Note(velocity=velocity, pitch=70, start=0.0, end=1.0))
    notes.append(
        pretty_midi.Note(velocity=velocity, pitch=80, start=1.0, end=2.0))
    notes.append(
        pretty_midi.Note(velocity=velocity, pitch=75, start=1.5, end=2.5))
    notes.append(
        pretty_midi.Note(velocity=velocity, pitch=60, start=5.1, end=5.34))

    return notes
Example #24
0
    def CodeToBass(self):
        bpm = self.bpm
        code_ls = self.code_ls
        beat = 60/bpm


        inst_pm_num = pretty_midi.instrument_name_to_program("Electric Bass (finger)")
        track = pretty_midi.Instrument(program=inst_pm_num)
        
        now = self.rug
        def Octave(note):
            if note in ["C","C#","D","D#","E","F"]:
                return 3
            else:
                return 2

        root1 = self.note_num_dic[self.code1[0]] + 12*Octave(self.code1[0])
        root4 = self.note_num_dic[self.code4[0]] + 12*Octave(self.code4[0])
        root5 = self.note_num_dic[self.code5[0]] + 12*Octave(self.code5[0])   
        
        now = self.rug
        root = root1
        for i in range(len(code_ls)):
            code = code_ls[i]
            
            #休符の時
            if code == "N":
                
                #直前にコードが存在すれば1拍ならす
                if i >= 1 and code_ls[i-1] in ["code1","code4","code5"]:
                    note = pretty_midi.Note(velocity = 100,pitch = root, start=now, end=now+beat*2)
                    track.notes.append(note)
                    now += beat*2

                #休符にする場合
                else:
                    now += beat*2
                    
            #コードが存在するとき
            else:
                if code == "code1":
                    root = root1
                elif code == "code4":
                    root = root4
                elif code == "code5":
                    root = root5
                
                for i in range(4):
                    note = pretty_midi.Note(velocity = 100,pitch = root, start=now, end=now+beat/2)
                    track.notes.append(note)
                    now += beat/2
                   
        return track
Example #25
0
    def CodeToPiano(self):
        bpm = self.bpm
        code_ls = self.code_ls
        beat = 60/bpm

        self.code1_num = self.CodeNumber(self.code1)
        self.code4_num = self.CodeNumber(self.code4)
        self.code5_num = self.CodeNumber(self.code5)

        inst_pm_num = pretty_midi.instrument_name_to_program("Acoustic Grand Piano")
        track = pretty_midi.Instrument(program=inst_pm_num)
        
        
        now = self.rug
        #本体
        codenum = self.code1_num
        for i in range(len(code_ls)):
            code = code_ls[i]

            #休符の時
            if code == "N":
                
                #直前にコードが存在すれば2拍ならす
                #codenumは直前のものが残る
                if i >= 1 and code_ls[i-1] in ["code1","code4","code5"]:
                    for j in range(3):
                        note = pretty_midi.Note(velocity = 100,pitch = codenum[j],start=now,end=now+beat*2)
                        track.notes.append(note)
                    now += beat*2

                #休符にする場合
                else:
                    now += beat* 2

            #コードが存在するとき
            else:
                if code == "code1":
                    codenum = self.code1_num
                elif code == "code4":
                    codenum = self.code4_num
                elif code == "code5":
                    codenum = self.code5_num
                
                #三種の音×2回
                for i in range(2):
                    for j in range(3):
                        note = pretty_midi.Note(velocity = 100,pitch = codenum[j],start=now,end=now+beat)
                        track.notes.append(note)
                    now += beat

        return track
 def save_as_midi(song, path="", name="default.mid", BPM = 120, velocity = 100):
     pm = pretty_midi.PrettyMIDI(resolution=960, initial_tempo=BPM) #pretty_midiオブジェクトを作ります
     instrument = pretty_midi.Instrument(0) #instrumentはトラックみたいなものです。
     for i,tones in enumerate(song):
         which_tone = torch.nonzero((tones == 1), as_tuple=False).reshape(-1)
         if len(which_tone) == 0:
             note = pretty_midi.Note(velocity=0, pitch=0, start=i, end=i+1) #noteはNoteOnEventとNoteOffEventに相当します。
             instrument.notes.append(note)
         else:
             for which in which_tone:
                 note = pretty_midi.Note(velocity=velocity, pitch=int(which), start=i, end=i+1) #noteはNoteOnEventとNoteOffEventに相当します。
                 instrument.notes.append(note)
     pm.instruments.append(instrument)
     pm.write(os.path.join(path, name)) #midiファイルを書き込みます。
Example #27
0
def test_4():

    print("[%s:%d] test_4()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    # Create a PrettyMIDI object
    cello_c_chord = pretty_midi.PrettyMIDI()
    # Create an Instrument instance for a cello instrument
    cello_program = pretty_midi.instrument_name_to_program('Cello')
    cello = pretty_midi.Instrument(program=cello_program)
    # Iterate over note names, which will be converted to note number later
    for note_name in ['C5', 'E5', 'G5']:
        # Retrieve the MIDI note number for this note name
        note_number = pretty_midi.note_name_to_number(note_name)
        # Create a Note instance for this note, starting at 0s and ending at .5s
        note = pretty_midi.Note(velocity=100,
                                pitch=note_number,
                                start=0,
                                end=.5)
        # Add it to our cello instrument
        cello.notes.append(note)
    # Add the cello instrument to the PrettyMIDI object
    cello_c_chord.instruments.append(cello)
    # Write out the MIDI data
    cello_c_chord.write('cello-C-chord.mid')
def create_scale(duration, silence, velocity, start=0):
    """
    Returns a list of notes in scale from 21 to 108 included.

    Arguments
    ---------
    duration : float
        the duration of each note in seconds
    silence : float
        the duration of the silence in between two notes
    velocity : int
        the velocity of each note
    start : float
        the start time of the scale in seconds

    Returns
    -------
    list :
        list of pretty_midi.Note
    float :
        the end of the scale in seconds
    """
    scale = []
    for i in range(21, 109):
        end = start + duration
        scale.append(pm.Note(velocity, i, start, end))
        start = end + silence

    return scale, end + silence
def melody_matrix2data(melody_matrix, tempo=120, start_time=0.0, get_list=False):
    ROLL_SIZE = 130
    HOLD_PITCH = 128
    REST_PITCH = 129
    melodyMatrix = melody_matrix[:, :ROLL_SIZE]
    melodySequence = [np.argmax(melodyMatrix[i]) for i in range(melodyMatrix.shape[0])]

    melody_notes = []
    minStep = 60 / tempo / 4
    onset_or_rest = [i for i in range(len(melodySequence)) if not melodySequence[i] == HOLD_PITCH]
    onset_or_rest.append(len(melodySequence))
    for idx, onset in enumerate(onset_or_rest[:-1]):
        if melodySequence[onset] == REST_PITCH:
            continue
        else:
            pitch = melodySequence[onset]
            start = onset * minStep
            end = onset_or_rest[idx + 1] * minStep
            noteRecon = pyd.Note(velocity=100, pitch=pitch, start=start_time + start, end=start_time + end)
            melody_notes.append(noteRecon)
    if get_list:
        return melody_notes
    else:
        melody = pyd.Instrument(program=pyd.instrument_name_to_program('Acoustic Grand Piano'))
        melody.notes = melody_notes
        return melody
Example #30
0
    def save(self, file_path, note_df):
        '''
        Save MIDI file.
        
        Args:
            file_path:    File path of MIDI.
            note_df:      `pd.DataFrame` of note data.
            
        '''

        chord = pretty_midi.PrettyMIDI()
        for program in note_df.program.drop_duplicates().values.tolist():
            df = note_df[note_df.program == program]
            midi_obj = pretty_midi.Instrument(program=program)
            for i in range(df.shape[0]):
                note = pretty_midi.Note(
                    velocity=int(df.iloc[i, :]["velocity"]),
                    pitch=int(df.iloc[i, :]["pitch"]),
                    start=float(df.iloc[i, :]["start"]), 
                    end=float(df.iloc[i, :]["end"])
                )
                # Add it to our cello instrument
                midi_obj.notes.append(note)
            # Add the cello instrument to the PrettyMIDI object
            chord.instruments.append(midi_obj)
        # Write out the MIDI data
        chord.write(file_path)