def notes2music(melody,
                time_per_duration,
                chord_progression=None,
                output_name='output/output.mid'):
    music_output = pretty_midi.PrettyMIDI(initial_tempo=tempo)
    piano_program = pretty_midi.instrument_name_to_program(
        'Electric Grand Piano')
    melody_instrument_name = random.choice([
        'Violin', 'Cello', 'Electric Grand Piano', 'Orchestral Harp', 'Trumpet'
    ])
    melody_instrument_program = pretty_midi.instrument_name_to_program(
        melody_instrument_name)

    melody_instrument = pretty_midi.Instrument(
        program=melody_instrument_program)
    piano = parse_notes2instrument(melody,
                                   melody_instrument,
                                   time_per_duration,
                                   velocity=100)
    music_output.instruments.append(piano)

    if chord_progression:
        chord_instrument = pretty_midi.Instrument(program=piano_program)
        chord_instrument = parse_notes2instrument(chord_progression,
                                                  chord_instrument,
                                                  time_per_duration,
                                                  velocity=100)
        music_output.instruments.append(chord_instrument)

    # Write out the MIDI data
    music_output.write(output_name)
示例#2
0
 def __init__(self, bpm: float) -> None:
     self.bpm = bpm
     self.data_fg: pretty_midi.Instrument = pretty_midi.Instrument(
         program=pretty_midi.instrument_name_to_program(
             "Acoustic Grand Piano"))
     self.data_bg: pretty_midi.Instrument = pretty_midi.Instrument(
         program=pretty_midi.instrument_name_to_program(
             "Acoustic Grand Piano"))
示例#3
0
def handy_functions():
    #note or instrument names to numbers
    pretty_midi.note_name_to_number('C4')
    pretty_midi.instrument_name_to_program('Cello')
    
    # shift pitches of notes
    for instrument in midi_data.instruments:
        if not instrument.is_drum:
            for note in instrument.notes:
                note.pitch += 5
示例#4
0
def write_piano_rolls_to_midi(piano_rolls,
                              filename='test.mid',
                              velocity=100,
                              tempo=120.0,
                              beat_resolution=24):

    program_nums = ["Electric Guitar (clean)", "Acoustic Bass", "Drums"]

    is_drum = [False, False, True]

    # Create a PrettyMIDI object
    midi = pretty_midi.PrettyMIDI(initial_tempo=tempo)
    # Iterate through all the input instruments
    for idx in range(len(piano_rolls)):
        # Create an Instrument object
        if idx == 0:
            instrument_program = pretty_midi.instrument_name_to_program(
                'Electric Guitar (clean)')
            instrument = pretty_midi.Instrument(program=instrument_program,
                                                is_drum=is_drum[idx])
            # Set the piano roll to the Instrument object

            set_piano_roll_to_instrument(piano_rolls[idx], instrument,
                                         velocity, tempo, beat_resolution)
            # Add the instrument to the PrettyMIDI object
            midi.instruments.append(instrument)

        if idx == 1:
            instrument_program = pretty_midi.instrument_name_to_program(
                'Acoustic Bass')
            instrument = pretty_midi.Instrument(program=instrument_program,
                                                is_drum=is_drum[idx])
            # Set the piano roll to the Instrument object

            set_piano_roll_to_instrument(piano_rolls[idx], instrument,
                                         velocity, tempo, beat_resolution)
            # Add the instrument to the PrettyMIDI object
            midi.instruments.append(instrument)

        if idx == 2:

            instrument = pretty_midi.Instrument(program=0,
                                                is_drum=is_drum[idx])
            # Set the piano roll to the Instrument object

            set_piano_roll_to_instrument(piano_rolls[idx], instrument,
                                         velocity, tempo, beat_resolution)

            # Add the instrument to the PrettyMIDI object
            midi.instruments.append(instrument)
    # Write out the MIDI data
    midi.write(filename)
示例#5
0
def main():
    parser = argparse.ArgumentParser('Generate validation response tracks from a trained call/response model')
    parser.add_argument(
        'dataset_path', help='path to the pickled dataset')
    parser.add_argument(
        'model_path', help='path to model builder')
    parser.add_argument(
        'output_path', help='path to output the results')
    parser.add_argument('min_len', help='minimum length', type=float)

    args = parser.parse_args()
    # create the model, then load the validation set created at training side
    # run validation through model
    model = EvalModel(expanduser(args.model_path))


    # build dataset
    print(args.dataset_path)
    dataset = build_dataset(args.dataset_path, model)

    #validation_calls = dataset['calls'][:, dataset['validation_indices'], :]
    #validation_responses = model.evaluate(validation_calls)

    print( dataset['training_indices'])

    training_calls = dataset['calls'][:, dataset['training_indices'], :]
    #print("training calls", training_calls)
    training_responses = model.evaluate(training_calls)

    call_program = pm.instrument_name_to_program('Acoustic Grand Piano')
    response_program = pm.instrument_name_to_program('Electric Grand Piano')

    def build_midi(call, response):
        midis = []
        for example_n in range(call.shape[1]):
            cur_call = call[:, example_n]
            midis.append(model.encoder.decode(cur_call, program=call_program))
            cur_response = response[:, example_n]
            midis.append(model.encoder.decode(cur_response, program=response_program))
        return concat(midis, args.min_len)

    full_set_path = join(expanduser(args.output_path), 'full_set.mid')
    build_midi(dataset['calls'], dataset['responses']).write(full_set_path)

    #validation_track_path = join(expanduser(args.output_path), 'validation.mid')
    #build_midi(validation_calls, validation_responses).write(validation_track_path)

    training_track_path = join(expanduser(args.output_path), 'training.mid')
    build_midi(training_calls, training_responses).write(training_track_path)
示例#6
0
def main():
    generated_path = os.getcwd() + '/midi_generated'
    for file in os.listdir('midi_generated'):
        if file.endswith('.json'):
            midi_obj = pretty_midi.PrettyMIDI()
            piano_program = pretty_midi.instrument_name_to_program(
                'Electric Piano 1')
            piano = pretty_midi.Instrument(program=piano_program)

            increment, notes_list = json_to_notes_list(generated_path + '/' +
                                                       file)
            curr_time = 0.0
            curr_notes = {}
            for chord in notes_list:
                ending_notes = curr_notes.keys() - set(chord)
                for note in ending_notes:
                    pm_note = pretty_midi.Note(velocity=60,
                                               pitch=note,
                                               start=curr_notes[note],
                                               end=curr_time)
                    del curr_notes[note]
                    piano.notes.append(pm_note)
                for note in chord:
                    if curr_notes.get(note) is None:
                        curr_notes[note] = curr_time
                curr_time += increment

            midi_obj.instruments.append(piano)
            midi_obj.write(generated_path + '/' + file[:-5] + '.mid')
示例#7
0
def patternLangSomethingClever(patterns):
    myMusic = pm.PrettyMIDI()

    for currPattern in patterns:
        # Create an Instrument instance for a cello instrument
        myMusicProgram = pm.instrument_name_to_program('cello')
        currInstr = pm.Instrument(program=myMusicProgram,
                                  name=currPattern['sampleLabel'])

        for i in range(currPattern['numRepeats']):
            currStartTime = currPattern[
                'start'] + i * currPattern['unitLengthSecs']
            currEndTime = currPattern['start'] + (
                i + 1) * currPattern['unitLengthSecs']
            recurseGrammar(pattern=currPattern['pattern'],
                           currRecursiveDepth=currPattern['recurse'],
                           startTime=currStartTime,
                           endTime=currEndTime,
                           instr=currInstr)

        myMusic.instruments.append(currInstr)

    myMusic.write("woahnow.mid")
    print("Wrote+returned midi in patternLangSomethingClever")
    # import pdb; pdb.set_trace()
    return myMusic
示例#8
0
def cut_midi(midi_data, start, end):

    new_midi = pm.PrettyMIDI(resolution=480)
    for instr in midi_data.instruments:
        new_instr = pm.Instrument(
            program=pm.instrument_name_to_program('Acoustic Grand Piano'),
            name=instr.name)
        for note in instr.notes:
            add_note = False
            if note.start <= start:
                if note.end > start:
                    # Note starts before start and ends after start, there is overlap
                    add_note = True
                else:
                    #Note starts and ends before start, no overlap
                    pass
            else:
                if note.start < end:
                    # Note starts between start and end, regardless of end there is overlap
                    add_note = True
                else:
                    # Note starts after end, no overlap
                    pass

            if add_note:
                new_note = pm.Note(note.velocity, note.pitch,
                                   max(0, note.start - start),
                                   min(end - start, note.end - start))
                if (new_note.start == 0 and new_note.end-new_note.start < 0.05) \
                or (new_note.end == end-start and new_note.end-new_note.start < 0.05):
                    # Do not add short notes at start or end of section
                    # that are due to imprecision in cutting.
                    pass
                else:
                    new_instr.notes.append(new_note)

        ccs_sorted = sorted(instr.control_changes, key=lambda x: x.time)
        cc64_on = False
        for cc in ccs_sorted:
            #Only keep sustain pedal
            if cc.number == 64:
                # Check if CC64 was on before start
                if cc.time < start:
                    cc64_on = cc.value > 64
                elif cc.time >= end:
                    break
                else:
                    if cc.time != start and cc64_on:
                        # Add extra CC to put sustain on
                        new_cc = pm.ControlChange(cc.number, cc.value, 0)
                        new_instr.control_changes.append(new_cc)
                        # Add extra CC just the first time
                        cc64_on = False
                    new_cc = pm.ControlChange(cc.number, cc.value,
                                              cc.time - start)
                    new_instr.control_changes.append(new_cc)

        new_midi.instruments.append(new_instr)

    return new_midi
示例#9
0
def get_midi_data(userNoteName, start, end):
    print('Time for', userNoteName, 'got:', time.time())
    if len(userNoteName) == 3:
        userNoteName = userNoteName[0] + '#' + userNoteName[2]
    primer = pretty_midi.PrettyMIDI()
    instrument = pretty_midi.Instrument(
        program=pretty_midi.instrument_name_to_program('Cello'))
    noteNumber = pretty_midi.note_name_to_number(userNoteName)
    try:
        note = pretty_midi.Note(velocity=100,
                                pitch=noteNumber,
                                start=int(start),
                                end=int(start) + int(end))
    except ValueError:
        return []
    instrument.notes.append(note)
    primer.instruments.append(instrument)
    output = generate_midi(primer, total_seconds=2)  # Takes about 4-6 seconds
    aiNotes = []
    try:
        note = output.instruments[0].notes[0]
        notePitch, noteStart, noteEnd = pretty_midi.note_number_to_name(
            note.pitch), note.start, note.end
        if len(notePitch) == 3:
            notePitch = notePitch[0] + 's' + notePitch[2]
        aiNotes.append((notePitch, noteStart, noteEnd))
        print('AI notes are', aiNotes)
        return aiNotes
    except IndexError:
        return []
示例#10
0
def write_midi_file_from_generated():
    f = filedialog.asksaveasfile(mode='w', defaultextension=".mid")
    if f:
        fname = f.name
        f.close()
        # Create a PrettyMIDI object
    piano_chord = pretty_midi.PrettyMIDI()
    # Create an Instrument instance for a cello instrument
    piano_program = pretty_midi.instrument_name_to_program(
        'Acoustic Grand Piano')
    piano = pretty_midi.Instrument(program=piano_program)
    generate = gen_music()
    start = 0
    for note in generate:
        note_number = int(iton[str(note)])
        duration = random.uniform(0.15, 0.45)
        note = pretty_midi.Note(velocity=100,
                                pitch=note_number,
                                start=start,
                                end=start + duration)
        piano.notes.append(note)
        start += duration

    # Add the piano instrument to the PrettyMIDI object
    piano_chord.instruments.append(piano)
    # Write out the MIDI data
    piano_chord.write(fname)
示例#11
0
def generate_note_midi(note_sequence,\
    instrument="Voice Oohs",\
    octave_offset=2):
    """ Given list of triples of the form (start_time, end_time, chord_name),
        generate midi file.
    Args:
        output_path (str): path to output midi file
        note_sequence (list): list of triples of the form
            (start_time, end_time, chord_name), with start_time, end_time in
            seconds, and MIDI note numbers
        instrument (str): General Midi instrument name. Defaults to piano.
    Returns:
        Nothing
    """

    midi = pretty_midi.PrettyMIDI()

    # Create an Instrument instance for chords
    guitar_program = pretty_midi.instrument_name_to_program(instrument)
    chords = pretty_midi.Instrument(program=guitar_program)

    # Iterate over note names, which will be converted to note number later
    for start_t,end_t,note in note_sequence:
        pm_note = pretty_midi.Note(velocity=100, pitch=note+12*octave_offset,
                                    start=start_t, end=end_t)
        chords.notes.append(pm_note)

    # Add the chords instrument to the PrettyMIDI object
    midi.instruments.append(chords)

    return midi
def convert_midi(seq, midi_path):
    midi_chord = pretty_midi.PrettyMIDI()

    midi_program = pretty_midi.instrument_name_to_program(
        'Lead 8 (bass + lead)')
    midi = pretty_midi.Instrument(program=midi_program)

    media_path = settings.BASE_DIR
    result_path = os.path.join(media_path, 'midiresult')

    midi_notes = []
    adding = 0

    if midi_path.endswith('.mid'):
        midi_data = pretty_midi.PrettyMIDI(midi_path)
        for instrument in midi_data.instruments:
            for note in instrument.notes:
                if note.start > 2.0:
                    note = pretty_midi.Note(velocity=note.velocity,
                                            pitch=note.pitch,
                                            start=note.start - 2.0,
                                            end=note.end - 2.0)
                    midi_notes.append(note)

    midi.notes.extend(midi_notes)
    midi_chord.instruments.append(midi)

    result_file = '{}.mid'.format(seq)
    midi_chord.write(os.path.join(result_path, result_file))
    return os.path.join(result_path, result_file)
示例#13
0
def sample(name, bars):
    model.eval()
    model.reset_cells()
    with torch.no_grad():
        samples = []
        
        # initialize the first z latent variable and the very first note (x0) which starts the melody 
        sample_z = torch.randn(1, 1, model.embedding_size).to(device)
        sample_x = torch.zeros(1, 1, model.input_size).to(device) #TODO: check if this is good or not

        # generate `bars` many beats
        for i in range(bars):
            sample = generate_beat(model, sample_x, sample_z)
            samples.append(sample.cpu())
            sample_z = torch.randn(1, 1, model.embedding_size).to(device) # sample new z
            sample_x = torch.unsqueeze(sample[:, -1, :], 0) # continue next beat from last sound of previous beat
        
        # generate piano roll from beats    
        all_samples = torch.cat(samples, 1)
        all_samples = all_samples * 60
        all_samples = torch.t(torch.squeeze(all_samples))

        # convert piano roll to midi
        program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano')
        #TODO: check what `fs` we should use here
        midi_from_proll = vae.midi_utils.piano_roll_to_pretty_midi(all_samples, fs = 16, program = program)

        # save midi to specified location
        save_path = f'../results/sample/sample_epoch_{name}.midi'
        midi_from_proll.write(save_path)
        print('Saved midi sample at {}'.format(save_path))

        torchvision.utils.save_image(all_samples, f'../results/sample/sample_epoch_{name}.png')
示例#14
0
def write_midi_file_from_generated(filename):
        # Create a PrettyMIDI object
    piano_chord = pretty_midi.PrettyMIDI()
    # Create an Instrument instance for a cello instrument
    piano_program = pretty_midi.instrument_name_to_program(
        'Acoustic Grand Piano')
    piano = pretty_midi.Instrument(program=piano_program)
    generate = gen_music()
    start = 0
    for note in generate:
        ref = iton[str(note)]
        if ref != 0:
            notes = [int(x) for x in iton[str(note)][1:-1].split(',') if x != '']
        else:
            notes = [0]
        duration = random.uniform(0.15, 0.45)        
        for n in notes:
            note = pretty_midi.Note(
                velocity=100, pitch=n, start=start, end=start+duration)
            piano.notes.append(note)
        start += duration

    # Add the piano instrument to the PrettyMIDI object
    piano_chord.instruments.append(piano)
    # Write out the MIDI data
    piano_chord.write(filename)
示例#15
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 transform(self, new_notes, instrument_type='Acoustic Grand Piano'):
     new_program = pretty_midi.instrument_name_to_program(instrument_type)
     new_instrument = pretty_midi.Instrument(new_program)
     new_file = pretty_midi.PrettyMIDI()
     new_instrument.notes = new_notes
     new_file.instruments.append(new_instrument)
     self.midi_file = new_file
示例#17
0
def fromFile(infilename="in.mid", outfilename='out.mid', drawGraph=False, outinstrument='Acoustic Grand Piano',
             debug=False):
    collect = collection(infilename)
    inoffset, inNotes = readinnotes(pretty_midi.PrettyMIDI(infilename), collect.secsperthirty)
    resu, inhil, outhil, inremain, outremain = collect.go(inNotes, drawGraph)
    if debug:
        for p, nl in inhil:
            print(p, '\t', ', '.join([str(nte) for nte in nl]))
        print("IN REMAINS")
        print([str(remain) for remain in inremain])
        print("------------------------------------------------------------")
        for plt, tm, nl in outhil:
            print(plt, '\t', tm, '\t', '[', ', '.join([str(nte) for nte in nl]), ']')
        print("OUT REMAINS")
        print([str(remain) for remain in outremain])
        print("------------------------------------------------------------")
    if len(resu) > 0:
        out_midi = pretty_midi.PrettyMIDI(initial_tempo=collect.raw_tempo)
        outinst = pretty_midi.Instrument(program=pretty_midi.instrument_name_to_program(outinstrument))
        if min([note.notenumber + inoffset for note in resu]) < tonic:
            inoffset += 12
        for note in resu:
            outNote = pretty_midi.Note(velocity=100, pitch=note.notenumber + inoffset, start=note.start, end=note.end)
            outinst.notes.append(outNote)
        out_midi.instruments.append(outinst)
        out_midi.write(outfilename)
示例#18
0
def song(string, my_name): # 'bpm120 C4 8 C3 A4 8 A4 8' # the number by itself is the length of the note before it. If no number for a note, then quarter note by default
    notes = string.split(' ')
    velocity = 100
    music = pretty_midi.PrettyMIDI()
    cello_program = pretty_midi.instrument_name_to_program('Cello')
    cello = pretty_midi.Instrument(program=cello_program)

    bpm = int(notes[0][3:])
    i = 1
    start = 0.0

    while i < len(notes):
        cur_note = notes[i]
        pitch_num = pretty_midi.note_name_to_number(cur_note)
        if i < len(notes) - 1 and notes[i+1].isdigit(): #check if next item is tempo, or just next note
            note_len = int(notes[i+1])
            i += 2
        else:
            note_len = 4 # default is quarter note
            i += 1
        note_len = 1.0 / note_len # quarter note (4) is actually 1/4
        end = start + get_note_length(bpm, note_len)
        new_note = pretty_midi.Note(velocity, pitch_num, start, end)
        cello.notes.append(new_note)
        start = end

    music.instruments.append(cello)

    update_wav(music, my_name)
    x = cello.notes
def generate_midi(data, filename):
    print('*' * 33)
    print('generate midi...')

    number_of_ts = len(data[0])

    music = pretty_midi.PrettyMIDI()

    for i in range(INSTRUMENTS):
        piano_program = pretty_midi.instrument_name_to_program(
            'Acoustic Grand Piano')
        piano = pretty_midi.Instrument(program=piano_program)

        for t in range(number_of_ts):
            for pitch in range(128):
                if data[i, t, pitch]:
                    start_time = t_to_time(music, t)
                    end_t = t + 1
                    while end_t < number_of_ts and data[i, end_t,
                                                        NUMBER_FEATURES - 3]:
                        end_t += 1
                    end_time = t_to_time(music, end_t)
                    # print('start_t:{}, end_t:{}'.format(t, end_t))
                    note = pretty_midi.Note(velocity=80,
                                            pitch=pitch,
                                            start=start_time,
                                            end=end_time)
                    piano.notes.append(note)

        music.instruments.append(piano)
    music.write(filename)
示例#20
0
    def __init__(self, instrument, bpm, velocity):
        self.dt4 = int((60 * 1000) / bpm)
        self.t = 0
        self.velocity = velocity

        program = pretty_midi.instrument_name_to_program(instrument)
        self.inst = pretty_midi.Instrument(program=program)
示例#21
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)
示例#22
0
def create_midi(path, notes):
    song = pretty_midi.PrettyMIDI()

    piano_program = pretty_midi.instrument_name_to_program(
        'Acoustic Grand Piano')
    piano = pretty_midi.Instrument(program=piano_program)

    current_time = 0
    for (type, length, pitch) in notes:
        length = float(length)
        pitch = int(pitch)
        num_octaves = pitch // 7
        note_number = num_octaves * 12 + c_major[pitch % 7] + 64
        note_number = min(max(0, note_number), 127)

        if (type == b'note'):
            note = pretty_midi.Note(velocity=100,
                                    pitch=note_number,
                                    start=current_time,
                                    end=current_time + length)
            piano.notes.append(note)

        current_time += length

    # Add the piano instrument to the PrettyMIDI object
    song.instruments.append(piano)
    song.write(path + '.mid')
示例#23
0
def _matrixToMidi(matrix, dest_path, transpose_octaves):
    #print("Converting matrix to MIDI")
    # 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)
    t = 0.0
    note_range = matrix.shape[1] - 2
    note_list = [np.where(r == 1)[0][0] for r in matrix[:, 0:note_range]
                 ]  # Convert one hot encoding to single integers
    n_notes = len(note_list)  # Number of consecutive notes
    output_notes = []
    for i in range(0, n_notes):
        p = note_list[i] + transpose_octaves * 12
        rest = matrix[i, note_range + 1]  # Rest before note
        s = t + rest  # Start = current time + rest before note
        d = matrix[i, note_range]
        t = s + d  #End = start + duration of note in seconds
        new_note = note.Note()
        new_note.pitch.midi = p
        #print(p)
        new_note.quarterLength = d
        new_note.offset = s
        new_note.storedInstrument = instrument.Piano()
        output_notes.append(new_note)
    midi_stream = stream.Stream(output_notes)
    midi_stream.write('midi', fp=dest_path)
    print("%d notes written to MIDI file" % (n_notes))
示例#24
0
def piano_roll_to_midi_mono(windows,
                            fs,
                            instrument_name='Acoustic Grand Piano',
                            allow_represses=False,
                            midi=None):
    if midi == None:
        print('h')
        midi = pretty_midi.PrettyMIDI()
    instrument_program = pretty_midi.instrument_name_to_program(
        instrument_name)
    instrument = pretty_midi.Instrument(program=instrument_program)
    cur_note = None  # an invalid note to start with
    cur_note_start = None
    clock = 0
    for i, step in enumerate(windows):
        note_num = np.argmax(step) - 1
        if note_num != cur_note or i == (len(windows) - 1):
            if (cur_note is not None and cur_note >= 0 and cur_note < 127):
                note = pretty_midi.Note(velocity=80,
                                        pitch=int(cur_note),
                                        start=cur_note_start,
                                        end=clock)
                instrument.notes.append(note)
            cur_note = note_num
            cur_note_start = clock
        clock = clock + 1.0 / fs
    midi.instruments.append(instrument)
    return midi
示例#25
0
def main():
    '''Main function'''

    instrument_program = pm.instrument_name_to_program(INSTRUMENT_NAME)
    for pitch in PITCH_RANGE:
        midi = pm.PrettyMIDI()
        inst = pm.Instrument(program=instrument_program)
        note = pm.Note(velocity=VELOCITY,
                       pitch=pitch,
                       start=0,
                       end=NOTE_LENGTH)

        inst.notes.append(note)
        midi.instruments.append(inst)

        with tempfile.NamedTemporaryFile(delete=False) as wav_file:
            wav_filename = wav_file.name
            numpy_type = 'float{}'.format(BIT_DEPTH)
            write(wav_file, SAMPLING_FREQUENCY,
                  midi.fluidsynth().astype(numpy_type))
        subprocess.run([
            'lame', '-b{}'.format(MP3_BIT_RATE), wav_filename,
            os.path.join(OUTPUT_DIR, '{:02d}.mp3'.format(pitch))
        ],
                       check=True)
示例#26
0
def note_df_to_pretty_midi(note_df, inst_name="Acoustic Grand Piano"):
    """Create a pretty_midi.PrettyMIDI object from a note DataFrame

    Notes
    -----
    See http://www.midi.org/techspecs/gm1sound.php
    """
    midi = pretty_midi.PrettyMIDI()
    quantum_time = 1 / 1000
    tracks = note_df.track.unique()
    if isinstance(inst_name, str):
        inst_name = {track: inst_name for track in tracks}
    for track, track_df in note_df.groupby("track"):
        track_inst_name = inst_name[track]
        inst_program = pretty_midi.instrument_name_to_program(track_inst_name)
        inst = pretty_midi.Instrument(program=inst_program)
        for _, row in track_df.iterrows():
            onset, pitch, dur = row[["onset", "pitch", "dur"]]
            start_time = quantum_time * onset
            end_time = quantum_time * (onset + dur)
            note = pretty_midi.Note(velocity=100,
                                    pitch=pitch,
                                    start=start_time,
                                    end=end_time)
            inst.notes.append(note)
        midi.instruments.append(inst)
    return midi
示例#27
0
def prettyMidiSingle(filename):
    pm = pretty_midi.PrettyMIDI(filename)
    notes = []
    for i in range(0, len(pm.instruments)):
        pm.instruments[i].remove_invalid_notes()
        print(pretty_midi.program_to_instrument_name(
            pm.instruments[i].program))
        print(len(pm.instruments[i].notes))
        print(pm.instruments[i].notes)
        notes.append(pm.instruments[i].notes)
        print("Pitch Bends", len(pm.instruments[0].pitch_bends))
        print("Control changes", len(pm.instruments[0].control_changes))
    print(len(notes))

    sample_Output = pretty_midi.PrettyMIDI()
    AcousticPiano = pretty_midi.instrument_name_to_program(
        'Acoustic Grand Piano')
    piano1 = pretty_midi.Instrument(program=AcousticPiano)
    piano2 = pretty_midi.Instrument(program=AcousticPiano)
    for note in notes[0]:
        piano1.notes.append(note)
    for note in notes[1]:
        piano2.notes.append(note)

    sample_Output.instruments.append(piano1)
    sample_Output.instruments.append(piano2)
    sample_Output.write("test_output_pretty_midi.mid")
    print("--------------------------------------------------")
示例#28
0
def to_midi(output,
            note_representation,
            instrument_name='Acoustic Grand Piano',
            start_note=60):
    midis = []
    for out in output:
        # Create a PrettyMIDI object
        midi = pretty_midi.PrettyMIDI()
        # Create an Instrument instance for a cello instrument
        instrument_program = pretty_midi.instrument_name_to_program(
            instrument_name)
        instrument = pretty_midi.Instrument(program=instrument_program)

        if note_representation == 'absolute':
            instrument.notes = _get_notes_absolute(out)
        elif note_representation == 'relative':
            instrument.notes = _get_notes_relative(out, start_note)
        else:
            raise Exception('{} is not a valid note_representation'\
                            .format(note_representation))

        # Add the cello instrument to the PrettyMIDI object
        midi.instruments.append(instrument)
        midis.append(midi)
    return midis
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
示例#30
0
def accompaniment_generator(outputpath, base_key, tempo, measure, n_passages):
    """
    Attribute
    outputpath: str, output file's path
    base_key: int, midi-note-number
    tempo: int
    measure: int, recommend 3 or 4
    n_passage: int, length of music
    melody: boolean, generate melody or not
    """
    assert base_key <= 60 and base_key >= 40, 'base_key is out of range'

    passage_time = measure/(tempo/60)    # passage time

    # create a PrettyMIDI object
    piano_chord = pm.PrettyMIDI(initial_tempo=tempo)
    # create an Instrument instance for a cello instrument (defined in constants.py)
    piano_program = pm.instrument_name_to_program('Orchestral Harp')
    piano = pm.Instrument(program=piano_program)

    INIT_STATE = 0
    cur_state = INIT_STATE
    chord_progression = []

    for i in range(0, n_passages):
        cur_state = get_next_state(STATE_PROB[cur_state])
        chord = [note + base_key for note in chords[cur_state]]

        put_rondo(piano, chord, i*passage_time, passage_time, 3)
        chord_progression.append([pm.note_number_to_name(note) for note in chord])

    piano_chord.instruments.append(piano)
    piano_chord.write(outputpath)
    return chord_progression
示例#31
0
def gen_midi(melodies, tempo):
    music_gen = pretty_midi.PrettyMIDI()
    piano_program = pretty_midi.instrument_name_to_program(
        "acoustic grand piano")
    piano = pretty_midi.Instrument(program=piano_program)
    for melody in melodies:
        runtime = 0
        for n in melody:
            # Retrieve the MIDI note number for this note name
            note_number = pretty_midi.note_name_to_number(n[0])
            length = (60 / tempo) * n[1]
            # Create a Note instance, starting at 0s and ending at .5s
            note = pretty_midi.Note(velocity=100,
                                    pitch=note_number,
                                    start=runtime,
                                    end=runtime + length)
            # Add it to our piano instrument
            piano.notes.append(note)
            #string_ens.notes.append(note)
            runtime += length
    # Add the instrument to the PrettyMIDI object
    music_gen.instruments.append(piano)
    #music_gen.instruments.append(string_ens)
    # Write out the MIDI data
    music_gen.write('generated_melody_primer.mid')
示例#32
0
def generate_chord_midi(chord_sequence,\
    melody_sequence=None,\
    instrument="Acoustic Grand Piano",\
    octave_offset=2,\
    tuning_offset=0,\
    voicings=None):
    """ Given list of triples of the form (start_time, end_time, chord_name),
        generate midi file.
    Args:
        output_path (str): path to output midi file
        chord_sequence (list): list of triples of the form
            (start_time, end_time, chord_name), with start_time, end_time in
            seconds, and chord names of the form 'A:min6', 'Bb:maj', etc
        instrument (str): General Midi instrument name. Defaults to piano.
    Returns:
        Nothing
    """

    if voicings is None:
        voicings = get_all_voicings(VOICING_FILE)

    midi_chords = pretty_midi.PrettyMIDI(initial_tempo=180.)

    # Create an Instrument instance for chords
    guitar_program = pretty_midi.instrument_name_to_program(instrument)
    chords = pretty_midi.Instrument(program=guitar_program)

    # Iterate over note names, which will be converted to note number later
    prev_voicing = None
    for triple in chord_sequence:
        start_t = triple[0]
        end_t = triple[1]
        notes = choose_voicing(triple[2], voicings, prev_voicing)
        prev_voicing = notes
        for n in notes:
            note = pretty_midi.Note(velocity=100, pitch=n+12*octave_offset+tuning_offset,
                                    start=start_t, end=end_t)
            chords.notes.append(note)

    if not melody_sequence is None:
        prev_n = None
        for start_t,end_t,n in melody_sequence:
            pc = int(n.replace('pc',''))
            p = coreutils.pc_oct_to_midi_note(pc=pc,octave=6,prev_note=prev_n)
            prev_n = p
            note = pretty_midi.Note(velocity=100, pitch=p,
                                    start=start_t, end=end_t)
            chords.notes.append(note)

    # Add the chords instrument to the PrettyMIDI object
    midi_chords.instruments.append(chords)

    return midi_chords
def pianoroll_to_midi(pianoroll, fs, program=1, filepath='midifile.mid',
                      scale=True, threshold=0):

    def isNoteEnd(pianoroll, note, end, threshold=np.inf):
        if end < pianoroll.shape[1] and pianoroll[note, end] > 0:
            if abs(pianoroll[note, end-1] - pianoroll[note, end]) <= threshold:
                return False
        return True

    # create PrettyMIDI object
    midifile = pm.PrettyMIDI(resolution=fs, initial_tempo=60 / (4.0/fs))
    # create Instrument instance
    if type(program) is not int:
        program = pm.instrument_name_to_program(program)
    instrument = pm.Instrument(program=program)
    # scale piano roll to [0, 127]
    if scale:
        pianoroll -= pianoroll.min()
        pianoroll = 127*(pianoroll / pianoroll.max())
        pianoroll = pianoroll.astype(int)
    # cumbersomely slow, refactor
    for note in range(pianoroll.shape[0]):
        start = 0
        end = 0
        while end < pianoroll.shape[1]:
            # find where note starts
            while start < pianoroll.shape[1] and pianoroll[note, start] == 0:
                start += 1
            if start == pianoroll.shape[1]:
                break

            end = start + 1
            # find where note ends
            while not isNoteEnd(pianoroll, note, end, threshold):
                end += 1

            # add note to instrument
            instrument.notes.append(pm.Note(
                velocity=pianoroll[note, start],
                pitch=note,
                start=start * 1.0/fs,
                end=end * 1.0/fs))
            start = end

    midifile.instruments.append(instrument)
    midifile.write(filepath)
示例#34
0
    def fluidsynth(self):
        """
        Returns an IPython.display.Audio object with samples rendered via
        fluidsynth with the Acoustic Grand Piano preset.

        You need fluidsynth, pyfluidsynth and pretty_midi installed for that to work.
        """
        import pretty_midi
        # Create a PrettyMIDI object
        pm = pretty_midi.PrettyMIDI()
        # Create an Instrument instance for a cello instrument
        piano_program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano')
        piano = pretty_midi.Instrument(program=piano_program)
        # Iterate over note names, which will be converted to note number later
        for note in self.notes:
            # Create a Note instance for this note, starting at 0s and ending at .5s
            note = pretty_midi.Note(velocity=70, pitch=note.pitch, start=self.tick_to_time(note.start), end=self.tick_to_time(note.end))
            # Add it to our cello instrument
            piano.notes.append(note)
        # Add the cello instrument to the PrettyMIDI object
        pm.instruments.append(piano)
        # Play
        audio_data = pm.fluidsynth()
        return display.Audio(audio_data, rate=44100)
示例#35
0
import pretty_midi
import itertools

# Our starting note/octave is middle C
base_note = 60

# Time between each chord
chord_duration = .1
# Length of each note
note_duration = chord_duration*.8

# Make a pretty midi object
pm = pretty_midi.PrettyMIDI()

# Add synth voice instrument
synth_voice = pretty_midi.instrument_name_to_program('Whistle')
pm.instruments.append(pretty_midi.Instrument(synth_voice))

# Keep track of timing
curr_time = 0.0
# All notes have velocity 100
velocity = 100

# itertools.combinations computes all pairs of items without replacement
for offset_1, offset_2 in itertools.combinations(range(1, 12), 2):
    # Create our chord from our three chord[n] values
    # Notes start at curr_time and end at curr_time + note_duration
    pm.instruments[0].notes.append(pretty_midi.Note(
        velocity, base_note, curr_time, curr_time + note_duration))
    pm.instruments[0].notes.append(pretty_midi.Note(
        velocity, base_note + offset_1, curr_time, curr_time + note_duration))
示例#36
0
文件: midi.py 项目: Jhird/nesmdb
def exprsco_to_midi(exprsco):
  import pretty_midi

  rate, nsamps, exprsco = exprsco

  # Create MIDI instruments
  p1_prog = pretty_midi.instrument_name_to_program('Lead 1 (square)')
  p2_prog = pretty_midi.instrument_name_to_program('Lead 2 (sawtooth)')
  tr_prog = pretty_midi.instrument_name_to_program('Synth Bass 1')
  no_prog = pretty_midi.instrument_name_to_program('Breath Noise')
  p1 = pretty_midi.Instrument(program=p1_prog, name='p1', is_drum=False)
  p2 = pretty_midi.Instrument(program=p2_prog, name='p2', is_drum=False)
  tr = pretty_midi.Instrument(program=tr_prog, name='tr', is_drum=False)
  no = pretty_midi.Instrument(program=no_prog, name='no', is_drum=True)

  # Iterate through score to extract channel notes
  notes = {}
  ccs = {}
  for i, ch in enumerate(np.split(exprsco, 4, axis=1)):
    ch = ch[:, 0, :]

    # MIDI doesn't allow velocity 0 messages so set tr velocity to 1
    if i == 2:
      ch[:, 1] = 1
      last_velocity = 1
    else:
      last_velocity = 0

    last_note = 0
    last_timbre = 0
    note_starts = []
    note_ends = []
    ch_ccs = []
    for s, (note, velocity, timbre) in enumerate(ch):
      if note != last_note:
        if note == 0:
          note_ends.append(s)
        else:
          if last_note == 0:
            note_starts.append((s, note, velocity))
          else:
            note_ends.append(s)
            note_starts.append((s, note, velocity))
      else:
        if velocity != last_velocity:
          ch_ccs.append((s, 11, velocity))

      if timbre != last_timbre:
        ch_ccs.append((s, 12, timbre))

      last_note = note
      last_velocity = velocity
      last_timbre = timbre
    if last_note != 0:
      note_ends.append(s + 1)

    assert len(note_starts) == len(note_ends)
    notes[i] = zip(note_starts, note_ends)
    ccs[i] = ch_ccs

  # Add notes to MIDI instruments
  for i, ins in enumerate([p1, p2, tr, no]):
    for (start_samp, note, velocity), end_samp in notes[i]:
      assert end_samp > start_samp
      start_t, end_t = start_samp / 44100., end_samp / 44100.
      note = pretty_midi.Note(velocity=velocity, pitch=note, start=start_t, end=end_t)
      ins.notes.append(note)

    for samp, cc_num, arg in ccs[i]:
      cc = pretty_midi.ControlChange(cc_num, arg, samp / 44100.)
      ins.control_changes.append(cc)

  # Add instruments to MIDI file
  midi = pretty_midi.PrettyMIDI(initial_tempo=120, resolution=22050)
  midi.instruments.extend([p1, p2, tr, no])

  # Create indicator for end of song
  eos = pretty_midi.TimeSignature(1, 1, nsamps / 44100.)
  midi.time_signature_changes.append(eos)

  # Write/read MIDI file
  mf = tempfile.NamedTemporaryFile('rb')
  midi.write(mf.name)
  midi = mf.read()
  mf.close()

  return midi
示例#37
0
def make_midi(time, flux, scale, duration,
              n_octaves=4, time_offset=0.0, note_min=48,
              lead_name='Distortion guitar',
              drum_name='Splash cymbal',
              midi_obj=None):

    if midi_obj is None:
        midi_obj = pretty_midi.PrettyMIDI()

    # Pick a voice
    program = pretty_midi.instrument_name_to_program(lead_name)
    inst = pretty_midi.Instrument(program=program)

    # Quantize the flux
    qflux = quantize_contour(get_contour(flux),
                             n_scale_tones=len(scale),
                             n_octaves=n_octaves)

    tones = note_min + np.add.outer(12 * np.arange(n_octaves), scale).ravel()

    # Iterate over note names, which will be converted to note number later
    time = time - time.min()

    time_scale = duration / float(time.max())

    time = time * time_scale + time_offset
    intervals = zip(time[:-1], time[1:])

    for t, note_t in zip(*sustain_tones(intervals, qflux)):

        # These are the zeros, skip them
        if note_t == note_min:
            continue

        # Create a Note instance for this note
        note = pretty_midi.Note(velocity=100,
                                pitch=tones[note_t],
                                start=t[0],
                                end=t[1])

        # Add it to our cello instrument
        inst.notes.append(note)

    # Add the cello instrument to the PrettyMIDI object
    midi_obj.instruments.append(inst)

    # Now do the percussion
    drum_beats = get_spikes(flux)
    program = 20
    note_t = pretty_midi.drum_name_to_note_number(drum_name)

    good_idx = librosa.peak_pick(drum_beats, 3, 3, 5, 5, 0.5, 10)

    inst = pretty_midi.Instrument(20, is_drum=True)

    for i in good_idx:
        t = intervals[i]
        note = pretty_midi.Note(velocity=100,
                                pitch=note_t,
                                start=t[0],
                                end=t[1])

        # Add it to our cello instrument
        inst.notes.append(note)

    midi_obj.instruments.append(inst)

    return midi_obj
示例#38
0
        # for the consequential 7 pitches, choose from trans
        for k in range(7):
                prev = pseq[k]
                while 1:
                        cur_ = numpy.random.choice(127,1,p=trans[prev])
                        cur = cur_[0]
                        if midichordscale[cur] == 1:
                                break
                pseq.append(cur)
        print pseq
        pseqseq.append(pseq)
        
# create midi files from pseq
guitar_c_chord = pretty_midi.PrettyMIDI()
# Create an Instrument instance for a guitar instrument
guitar_program = pretty_midi.instrument_name_to_program('Electric Guitar (jazz)')
guitar = pretty_midi.Instrument(program=guitar_program)
# Iterate over note names, which will be converted to note number later
bartime = 0
print timeseq
for i in range(len(pseqseq)):
        
        # first play the chord
        ct = ctseq[i]
        chordtones = []
        for j in range(12):
                if ct[j] == 1:
                        chordtones.append(j+60)
        print chordtones
        for note_number in chordtones:
            note = pretty_midi.Note(velocity=70, pitch=note_number, start=timeseq[i], end=timeseq[i+1])