Exemplo n.º 1
0
def key_name_to_notes(key, octave_start=1, number_of_octaves=4):
    """ Convert a key name to notes, using C3=60

    :param key: String matching one of the values in pre-defined KEY dict
    :param octave_start: octave for the first note, as defined by C3=60
    :param number_of_octaves: The number of octaves to include in the list
    :return:
    """
    key = KEYS.get(key)
    if not key:
        raise ValueError('No key by that name found')

    notes = []
    octave = octave_start + 1
    while len(notes) < number_of_octaves * 7:
        for note in key:
            note_with_octave = note + str(octave)
            note_number = note_name_to_number(note_with_octave)
            if note_number % 12 == 0 and len(notes) != 0:
                octave += 1
                note_with_octave = note + str(octave)
                note_number = note_name_to_number(note_with_octave)
            notes.append(note_number)

    return notes
Exemplo n.º 2
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
Exemplo n.º 3
0
    def __init__(self,
                 midi_folder_path,
                 longest_sequence_length=None,
                 lowest_note="C3",
                 highest_note="C7"):
        self.lowest_note_num = pretty_midi.note_name_to_number(lowest_note)
        self.highest_note_num = pretty_midi.note_name_to_number(highest_note)
        self.num_notes = self.highest_note_num - self.lowest_note_num
        self.midi_folder_path = midi_folder_path
        # TODO(gizatt) Make this recursive within the training
        # folder for better organization.
        midi_filenames = os.listdir(midi_folder_path)
        self.longest_sequence_length = longest_sequence_length
        midi_full_filenames = map(
            lambda filename: os.path.join(midi_folder_path, filename),
            midi_filenames)
        self.midi_full_filenames = list(midi_full_filenames)

        # Preload all data. We'll never have *that* much.
        def load_piano_roll(filename):
            print("Loading %s" % filename)
            piano_roll, tempos = midi_filename_to_piano_roll(filename)
            # Cut down to the selected note range
            return piano_roll[self.lowest_note_num:self.highest_note_num, :]

        self.piano_rolls = [
            load_piano_roll(filename) for filename in self.midi_full_filenames
        ]

        if longest_sequence_length is None:
            self.longest_sequence_length = max(roll.shape[1]
                                               for roll in self.piano_rolls)
Exemplo n.º 4
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)
Exemplo n.º 5
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) .')
Exemplo n.º 6
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
Exemplo n.º 7
0
def gen_music():
    #gen music here
    #file_save("music")
    model = torch.load(MODEL_PATH)
    model.eval()
    model.to(device)
    notes = []
    note = comboNote1.get()
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[noteNo])
    note = comboNote2.get()
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[noteNo])
    note = comboNote3.get()
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[noteNo])
    note = comboNote4.get()
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[noteNo])
    note = comboNote5.get()
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[noteNo])
    generate = generate_from_one_note(notes)

    for i in range(195):
        output = torch.exp(model(torch.tensor([generate]).to(device)))
        newarr = [i[0] for i in output[0]]
        if tobeam.get():
            beam = {}
            for j in range(3):
                c = Categorical(torch.tensor(newarr))
                next_note = c.sample()
                beam[next_note.item()] = newarr[next_note.item()]
            for k in beam:
                arr = copy.deepcopy(generate)
                arr.pop(0)
                arr.append(k)
                instance_out = torch.exp(model(torch.tensor([arr]).to(device)))
                instarr = [i[0] for i in instance_out[0]]
                c = Categorical(torch.tensor(instarr))
                next_note = c.sample()
                beam[k] = beam[k] * instarr[next_note.item()]
            generate.pop(0)
            generate.append(max(beam.items(), key=operator.itemgetter(1))[0])
        else:
            c = Categorical(torch.tensor(newarr))
            next_note = c.sample()
            generate.pop(0)
            generate.append(next_note.item())
    return generate
Exemplo n.º 8
0
def gen_music():
    # gen music here
    # file_save("music")
    model = torch.load(MODEL_PATH, map_location=device)
    model.eval()
    model.to(device)
    notes = []
    note = starting_notes[0]
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[f'({noteNo},)'])
    note = starting_notes[1]
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[f'({noteNo},)'])
    note = starting_notes[2]
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[f'({noteNo},)'])
    note = starting_notes[3]
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[f'({noteNo},)'])
    note = starting_notes[4]
    noteNo = str(pretty_midi.note_name_to_number(note))
    notes.append(ntoi[f'({noteNo},)'])
    generate = generate_from_one_note(notes)

    for i in tqdm.tqdm(range(song_len-5)):
        output = torch.exp(model(torch.tensor([generate]).to(device)))
        newarr = [i[0] for i in output[0]]
        if do_beam:
            beam = {}
            for j in range(3):
                c = Categorical(torch.tensor(newarr))
                next_note = c.sample()
                beam[next_note.item()] = newarr[next_note.item()]
            for k in beam:
                arr = copy.deepcopy(generate)
                arr.pop(0)
                arr.append(k)
                instance_out = torch.exp(model(torch.tensor([arr]).to(device)))
                instarr = [i[0] for i in instance_out[0]]
                c = Categorical(torch.tensor(instarr))
                next_note = c.sample()
                beam[k] = beam[k]*instarr[next_note.item()]
            generate.pop(0)
            generate.append(max(beam.items(), key=operator.itemgetter(1))[0])
        else:
            c = Categorical(torch.tensor(newarr))
            next_note = c.sample()
            generate.pop(0)
            generate.append(next_note.item())
    return generate
Exemplo n.º 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 []
Exemplo n.º 10
0
    def add_notes(self, note_list, instrument_num=0, interval=.5):
        '''
        add notes to instrum √
        support Note ,Pretty_Note,String
        '''
        if len(self.pm.instruments) - 1 < instrument_num:
            pass

        if note_list:
            curr_time = self.pm.instruments[instrument_num].current_time

            if isinstance(note_list[0], basestring):
                for note_name in note_list:
                    # 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 ,velocity random in  45 - 70
                    note = pretty_midi.Note(
                        velocity=random.randint(45, 70), pitch=note_number,
                        start=curr_time, end=curr_time + interval)
                    self.pm.instruments[instrument_num].notes.append(note)
                    curr_time += interval

            elif isinstance(note_list[0], Note) or isinstance(note_list[0], P_NODE):
                for note in note_list:
                    self.pm.instruments[instrument_num].notes.append(note)

            else:
                raise Exception(
                    '[-] Got a type : %s wrong note type ,except Note or String ' % type(note_list[0]))
            self.pm.instruments[instrument_num].current_time = curr_time
Exemplo n.º 11
0
def get_scale(note_name, scale):
    note_number = pretty_midi.note_name_to_number(note_name)
    list_notes = [note_number]
    for mode in scale:
        list_notes.append(note_number + mode)
    print(list_notes)
    return list_notes
Exemplo n.º 12
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
Exemplo n.º 13
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')
Exemplo n.º 14
0
    def to_notes(self, scale: int) -> List[pretty_midi.Note]:
        notes = []
        beat_length_list_list = [
            self._bar_to_beat_length_list(score_object_list)
            for score_object_list in self.score_object_lists
        ]
        beat_length_list = self._merge_beat_length_list(beat_length_list_list)
        bpm_multiplexer = 60 / self.bpm
        current_position = 0
        for beat_length in beat_length_list:
            if isinstance(beat_length.kind, Chord):
                for note in beat_length.kind.to_notes(scale):
                    note_number = pretty_midi.note_name_to_number(note)
                    note = pretty_midi.Note(
                        velocity=100,
                        pitch=note_number,
                        start=current_position + random.random() * 0.03,
                        end=current_position +
                        beat_length.length * bpm_multiplexer,
                    )
                    notes.append(note)
            current_position += beat_length.length * bpm_multiplexer
            if (current_position * 44100 * 16 * 2 / 8 >
                    8388608 * 5):  # あとでmp3に変換するようにしたのでかなりゆるくした
                raise ChordiumException("長すぎます!")

        return notes
Exemplo n.º 15
0
def makeNote(note, startTime, endTime):
    note_number = pretty_midi.note_name_to_number(note)
    note = pretty_midi.Note(velocity=100,
                            pitch=note_number,
                            start=startTime,
                            end=endTime)
    return note
Exemplo n.º 16
0
    def __init__(self, piano_midi, key, sequence_length=16, binarize=True):
        self.sequence_length = sequence_length

        if key:
            ## get the key of the music (by estimating the dominant semitone)
            #total_velocity = sum(sum(piano_midi.get_chroma()))
            #semitones = [sum(semitone)/total_velocity for semitone in piano_midi.get_chroma()]
            #midi_key = np.argmax(semitones)

            ## Shift all notes down by midi_key semitones if major, midi_key + 3 semitones if minor
            ##transpose_key = midi_key if semitones[(midi_key + 4) % 12] > semitones[(midi_key + 3) % 12] else midi_key + 3
            #transpose_key = 0 #TODO: temporarly disabled transposition of pitches

            transpose_key = pretty_midi.note_name_to_number(key.tonic.name.replace('-','b')+'0') - 12 + (0 if key.mode=="major" else 3)

            # Shift all notes down by transpose_key semitones
            for instrument in piano_midi.instruments:
                for note in instrument.notes:
                    note.pitch -= transpose_key if note.pitch - transpose_key >= 0 else transpose_key - 12

        # this is the required sampling frequency to get 16 x 16th notes in a bar (1 bar = 4 beats)
        fs = (piano_midi.estimate_tempo() * 16.0) / (4.0 * 60.0)

        self.piano_roll = piano_midi.get_piano_roll(fs=fs)[21:109, :]
        self.piano_roll = self.piano_roll.astype(np.float32)
        # binarize if set
        if binarize:
            self.piano_roll = np.clip(self.piano_roll, 0, 1)

        self.piano_roll = np.transpose(self.piano_roll)
Exemplo n.º 17
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')
Exemplo n.º 18
0
def make_random_song(file,
                     lmb_start=50,
                     lmb_stop=1,
                     seed=0,
                     tempo=120,
                     res=960,
                     len_t=1000):
    '''
    ポアソン過程でランダムな曲を作って、midiファイルに出力します。
    file <str> :出力midiファイル名
    lmb_start <float or list/array_of_float(len==128)> : note off から次の note on までの平均秒数
    lmb_stop <float or list/array_of_float(len==128)> : note on から note off までの平均秒数
    seed <int> : np.random.seedに渡す乱数の種
    tempo <int> : テンポ
    res <int> : レゾリューション
    len_t <float> : 生成される曲の秒数(の上限)
    '''
    np.random.seed(seed)
    pm = pretty_midi.PrettyMIDI(resolution=res,
                                initial_tempo=tempo)  #pretty_midiオブジェクトを作ります
    instrument = pretty_midi.Instrument(0)  #instrumentはトラックに相当します。

    if (isinstance(lmb_start, int) or isinstance(lmb_start, float)):
        lmb_start = [lmb_start for i in range(128)]
    if (isinstance(lmb_stop, int) or isinstance(lmb_stop, float)):
        lmb_stop = [lmb_stop for i in range(128)]

    low_pitch = pretty_midi.note_name_to_number('A0')
    high_pitch = pretty_midi.note_name_to_number('A8')

    for note_number in range(low_pitch, high_pitch):
        t = 0.
        while t <= len_t:
            start = np.random.exponential(lmb_start[note_number]) + t
            stop = np.random.exponential(lmb_stop[note_number]) + start
            t = stop
            if t > len_t:
                break
            note = pretty_midi.Note(
                velocity=np.random.randint(50, 127),
                pitch=note_number,
                start=start,
                end=stop)  #noteはNoteOnEventとNoteOffEventに相当します。
            instrument.notes.append(note)

    pm.instruments.append(instrument)
    pm.write(file)  #midiファイルを書き込みます。
Exemplo n.º 19
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())
Exemplo n.º 20
0
def getMelody(gpv_df):
    """
    概要: GPVデータのデータフレームから、各変数の変化を表現する音声ファイルを作成する
    @param gpv_df: 対象値に最も近いメッシュ上のGPVデータのdataframe
    @return GPVデータから作成したmidiファイル
    """

    #pretty_midiオブジェクトの作成
    pm = pretty_midi.PrettyMIDI(resolution=960, initial_tempo=120)

    # 各変数に楽器を割り当て、奏でる音階を値の変化から決定する
    for n in range(0, len(gpv_df.index), 1):
        # 楽器の割り当て、listは楽器の種別が重ならない様にするための工夫です
        instrument_list = [x * 5 for x in range(0, 11, 1)]
        instrument = pretty_midi.Instrument(instrument_list[n])

        # 最小値0,最大値1にMin-Max Normalization
        gpv_df_norm = gpv_df.apply(lambda x: ((x - x.min()) /
                                              (x.max() - x.min())),
                                   axis=1)
        for t in range(0, len(gpv_df), 1):
            tmp = gpv_df_norm.iloc[n, t]
            if 0 <= tmp and tmp <= 1 / 8:
                note_number = pretty_midi.note_name_to_number('C4')
            elif 1 / 8 < tmp and tmp <= 2 / 8:
                note_number = pretty_midi.note_name_to_number('D4')
            elif 2 / 8 < tmp and tmp <= 3 / 8:
                note_number = pretty_midi.note_name_to_number('E4')
            elif 3 / 8 < tmp and tmp <= 4 / 8:
                note_number = pretty_midi.note_name_to_number('F4')
            elif 4 / 8 < tmp and tmp <= 5 / 8:
                note_number = pretty_midi.note_name_to_number('G4')
            elif 5 / 8 < tmp and tmp <= 6 / 8:
                note_number = pretty_midi.note_name_to_number('A4')
            elif 6 / 8 < tmp and tmp <= 7 / 8:
                note_number = pretty_midi.note_name_to_number('B4')
            elif 7 / 8 < tmp and tmp <= 1:
                note_number = pretty_midi.note_name_to_number('C5')
            else:
                # 全ての値が0の場合適当な音を(正規化の段階でNanとなるため)
                note_number = pretty_midi.note_name_to_number('C5')

            note = pretty_midi.Note(velocity=100,
                                    pitch=note_number,
                                    start=t,
                                    end=t + 1)
            instrument.notes.append(note)
        pm.instruments.append(instrument)
    pm.write('output/midi/test.mid')  #midiファイルを書き込みます。

    return gpv_df_norm
Exemplo n.º 21
0
    def to_protobuf(self):
        """Protocol Buffer output."""
        # TODO(ryanstauffer): Confirm that we need this
        note = music_pb2.NoteSequence.Note()
        note.pitch = pretty_midi.note_name_to_number(self.name)
        note.denominator = self.length

        return note
Exemplo n.º 22
0
def convert_notes():
    # Iterate over note names, which will be converted to note number later
    note_list = []
    for note_name in read_notes():
        # Retrieve the MIDI note number for this note name
        note_number = pretty_midi.note_name_to_number(note_name)
        note_list.append(note_number)
    return note_list
Exemplo n.º 23
0
def add_chord_to_instrument(chord, start_position, length, instrument):
    for note_name in chord:
        note_number = pretty_midi.note_name_to_number(note_name)
        note = pretty_midi.Note(velocity=100,
                                pitch=note_number,
                                start=start_position,
                                end=(start_position + length))
        instrument.notes.append(note)
Exemplo n.º 24
0
def add_tone_to_instrument(tone, start_position, length, instrument):
    note_number = pretty_midi.note_name_to_number(tone)
    print([tone, note_number])
    note = pretty_midi.Note(velocity=100,
                            pitch=note_number,
                            start=start_position,
                            end=(start_position + length))
    instrument.notes.append(note)
Exemplo n.º 25
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)
Exemplo n.º 26
0
def get_midi_data(userNoteName, start, end):
	# Just generate one for now
	primer = pretty_midi.PrettyMIDI()
	instrument = pretty_midi.Instrument(program=pretty_midi.instrument_name_to_program('Cello'))
	noteNumber = pretty_midi.note_name_to_number(userNoteName)
	note = pretty_midi.Note(velocity=100, pitch=noteNumber, start=start, end=end)
	instrument.notes.append(note)
	output = generate_midi(primer, total_seconds=2)
	pianoRoll = output.get_piano_roll()
	
	subArrays = np.split(pianoRoll, [48, 81])
	first = subArrays[1]
	second = np.split(subArrays[2], [12, 15])[1]
	ofInterest = np.concatenate((first, second))
	listOfInterest = ofInterest.tolist()
	# for subList in listOfInterest:
	numZeros = 0
	others = 0
	aiNotes = []
	for noteIndex, timeList in enumerate(pianoRoll.tolist()):
		startTime = None
		endTime = None
		lastVal = 0
		for timeIndex, value in enumerate(timeList):
			timeIndex = timeIndex * 10
			if value != 0:
				# This note is on at timeIndex
				if lastVal == 0:
					# First timeIndex for this note
					startTime = timeIndex
			elif lastVal != 0:
				# Note was on and is now off. Add to list of notes
				endTime = timeIndex
				noteName = pianoRollToNoteName.get(noteIndex)
				if noteName is None:
					pass
					#print('Ignoring note at midi value', noteIndex)
				else:
					aiNotes.append((noteName, startTime, endTime))
					#print('added note', noteName, 'with start and end', startTime, endTime)
					startTime = None
					endTime = None

			# if item != 0 and item != 0.0:
			# 	print('in sublist', noteIndex, 'at index', index, 'means note is', pianoRollToNoteName.get(noteIndex))
			lastVal = value
	if lastVal != 0:
		endTime = timeIndex
		noteName = pianoRollToNoteName.get(noteIndex)
		if noteName is None:
			pass
			#print('Ignoring note at midi value', noteIndex)
		else:
			aiNotes.append((noteName, startTime, endTime))
			#print('added note', noteName, 'with start and end', startTime, endTime)
			startTime = None
			endTime = None				
	return sorted(aiNotes, key=lambda x:x[1])
Exemplo n.º 27
0
    def seq_to_midi_rhythm(self, rhythm, c=['C5', 'D5']):

        for note_name, _rhythm in zip(c, rhythm):
            # 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=66, pitch=note_number, start=_rhythm[0], end=_rhythm[1])
            self.pm.instruments[0].notes.append(note)
Exemplo n.º 28
0
def change_to_inner_tone(chord, tone):
	most_near = [100, "x"]
	num = [-12, 12, 0]
	for c in chord:
		for n in num:
			c_num = pretty_midi.note_name_to_number(c)+n
			if abs(c_num-tone)<=(most_near[0]):
				most_near = [abs(c_num-tone), c_num]
	return most_near[1]
Exemplo n.º 29
0
def decode_note_notation(note_string):
    '''Turn a string note into a list of its attributes'''
    note = re.search('i(.*):v(.*):(.*):s(.*):e(.*)', note_string)
    instrument = int(note.group(1))
    velocity = int(note.group(2))
    pitch = pretty_midi.note_name_to_number(note.group(3))
    start = float(note.group(4))
    end = float(note.group(5))
    return [instrument, velocity, pitch, start, end]
Exemplo n.º 30
0
 def set_accompaniment(self):
     accompaniment = [
         '', 'A3', 'A3', 'F#4', 'F#4', 'G4', 'G4', 'F#4', 'F#4', 'E4', 'E4',
         'D4', 'D4', 'A3', 'C#4', 'D4', 'D4'
     ]
     self.accompaniment = [
         {pretty_midi.note_name_to_number(note)} if note != '' else ''
         for note in accompaniment
     ]
Exemplo n.º 31
0
#!/usr/local/bin/python
import sys
import pretty_midi
midi_data = pretty_midi.PrettyMIDI('drums.mid')


pr = midi_data.instruments[0].get_piano_roll().tolist()
pr_len = len(pr[0])
new_pr = []
print pr_len
for i in range(0,pr_len):
	tmp_pr = []
	for j in range(0,127):
		if pr[j][i] > 0:
			if midi_data.instruments[0].is_drum:
				tmp_pr.append(pretty_midi.note_number_to_drum_name(j))
			else:
				tmp_pr.append(pretty_midi.note_number_to_name(j))
	new_pr.append(tmp_pr)
print new_pr

# Synthesize the resulting MIDI data using sine waves
#audio_data = midi_data.synthesize()

print pretty_midi.note_name_to_number("C3")