本文整理汇总了Python中pretty_midi.Instrument方法的典型用法代码示例。如果您正苦于以下问题:Python pretty_midi.Instrument方法的具体用法?Python pretty_midi.Instrument怎么用?Python pretty_midi.Instrument使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pretty_midi
的用法示例。
在下文中一共展示了pretty_midi.Instrument方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: piano_roll_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def piano_roll_to_midi(piano_roll, sample_rate):
"""Convert the piano roll to a PrettyMIDI object.
See: http://github.com/craffel/examples/reverse_pianoroll.py
"""
midi = pretty_midi.PrettyMIDI()
instrument = pretty_midi.Instrument(0)
midi.instruments.append(instrument)
padded_roll = np.pad(piano_roll, [(1, 1), (0, 0)], mode='constant')
changes = np.diff(padded_roll, axis=0)
notes = np.full(piano_roll.shape[1], -1, dtype=np.int)
for tick, pitch in zip(*np.where(changes)):
prev = notes[pitch]
if prev == -1:
notes[pitch] = tick
continue
notes[pitch] = -1
instrument.notes.append(pretty_midi.Note(
velocity=100,
pitch=pitch,
start=prev / float(sample_rate),
end=tick / float(sample_rate)))
return midi
示例2: decode_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def decode_to_midi(self, pianoroll):
"""Decodes pianoroll into midi."""
# NOTE: Assumes four separate instruments ordered from high to low.
midi_data = pretty_midi.PrettyMIDI()
duration = self.qpm / 60 * self.shortest_duration
tt, pp, ii = pianoroll.shape
for i in range(ii):
notes = []
for p in range(pp):
for t in range(tt):
if pianoroll[t, p, i]:
notes.append(
pretty_midi.Note(
velocity=100,
pitch=self.min_pitch + p,
start=t * duration,
end=(t + 1) * duration))
notes = merge_held(notes)
instrument = pretty_midi.Instrument(program=self.programs[i] - 1)
instrument.notes.extend(notes)
midi_data.instruments.append(instrument)
return midi_data
示例3: write_piano_rolls_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def write_piano_rolls_to_midi(piano_rolls, program_nums=None, is_drum=None, filename='test.mid', velocity=100,
tempo=120.0, beat_resolution=24):
if len(piano_rolls) != len(program_nums) or len(piano_rolls) != len(is_drum):
print("Error: piano_rolls and program_nums have different sizes...")
return False
if not program_nums:
program_nums = [0, 0, 0]
if not is_drum:
is_drum = [False, False, False]
# 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
instrument = pretty_midi.Instrument(program=program_nums[idx], 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)
示例4: set_piano_roll_to_instrument
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def set_piano_roll_to_instrument(piano_roll, instrument, velocity=100, tempo=120.0, beat_resolution=24):
# Calculate time per pixel
tpp = 60.0/tempo/float(beat_resolution)
# Create piano_roll_search that captures note onsets and offsets
piano_roll = piano_roll.reshape((piano_roll.shape[0] * piano_roll.shape[1], piano_roll.shape[2]))
piano_roll_diff = np.concatenate((np.zeros((1,128),dtype=int), piano_roll, np.zeros((1,128),dtype=int)))
piano_roll_search = np.diff(piano_roll_diff.astype(int), axis=0)
# Iterate through all possible(128) pitches
for note_num in range(128):
# Search for notes
start_idx = (piano_roll_search[:,note_num] > 0).nonzero()
start_time = tpp*(start_idx[0].astype(float))
end_idx = (piano_roll_search[:,note_num] < 0).nonzero()
end_time = tpp*(end_idx[0].astype(float))
# Iterate through all the searched notes
for idx in range(len(start_time)):
# Create an Note object with corresponding note number, start time and end time
note = pretty_midi.Note(velocity=velocity, pitch=note_num, start=start_time[idx], end=end_time[idx])
# Add the note to the Instrument object
instrument.notes.append(note)
# Sort the notes by their start time
instrument.notes.sort(key=lambda note: note.start)
示例5: write_piano_rolls_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def write_piano_rolls_to_midi(piano_rolls, program_nums=None, is_drum=None, filename='test.mid', velocity=100, tempo=120.0, beat_resolution=24):
if len(piano_rolls) != len(program_nums) or len(piano_rolls) != len(is_drum):
print( "Error: piano_rolls and program_nums have different sizes...")
return False
if not program_nums:
program_nums = [0, 0, 0]
if not is_drum:
is_drum = [False, False, False]
# 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
instrument = pretty_midi.Instrument(program=program_nums[idx], 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)
示例6: to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def to_midi(notes, t_unit=0.02):
midi = pretty_midi.PrettyMIDI()
piano = pretty_midi.Instrument(program=0)
l, u = find_min_max_stren(notes)
s_low = 60
s_up = 127
v_map = lambda stren: int(s_low+((s_up-s_low)*((stren-l)/(u-l+0.0001))))
low_b = note_to_midi("A0")
coll = set()
for nn in notes:
pitch = nn["pitch"] + low_b
start = nn["start"] * t_unit
end = nn["end"] * t_unit
volume = v_map(nn["stren"])
coll.add(pitch)
m_note = pretty_midi.Note(velocity=volume, pitch=pitch, start=start, end=end)
piano.notes.append(m_note)
midi.instruments.append(piano)
return midi
示例7: extract_drums
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def extract_drums(midi_path: str) -> Optional[PrettyMIDI]:
"""
Extracts a PrettyMIDI instance of all the merged drum tracks
from the given MIDI path.
:param midi_path: the path to the MIDI file
:return: the PrettyMIDI instance of the merged drum tracks
"""
os.makedirs(args.path_output_dir, exist_ok=True)
pm = PrettyMIDI(midi_path)
pm_drums = copy.deepcopy(pm)
pm_drums.instruments = [instrument for instrument in pm_drums.instruments
if instrument.is_drum]
if len(pm_drums.instruments) > 1:
# Some drum tracks are split, we can merge them
drums = Instrument(program=0, is_drum=True)
for instrument in pm_drums.instruments:
for note in instrument.notes:
drums.notes.append(note)
pm_drums.instruments = [drums]
if len(pm_drums.instruments) != 1:
raise Exception(f"Invalid number of drums {midi_path}: "
f"{len(pm_drums.instruments)}")
return pm_drums
开发者ID:PacktPublishing,项目名称:hands-on-music-generation-with-magenta,代码行数:26,代码来源:chapter_06_example_00.py
示例8: to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def to_midi(self, program=DEFAULT_SAVING_PROGRAM,
resolution=DEFAULT_RESOLUTION, tempo=DEFAULT_TEMPO):
midi = PrettyMIDI(resolution=resolution, initial_tempo=tempo)
inst = Instrument(program, False, 'NoteSeq')
inst.notes = copy.deepcopy(self.notes)
midi.instruments.append(inst)
return midi
示例9: write_piano_roll_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def write_piano_roll_to_midi(piano_roll, filename, program_num=0, is_drum=False, velocity=100,
tempo=120.0, beat_resolution=16):
# Create a PrettyMIDI object
midi = pretty_midi.PrettyMIDI(initial_tempo=tempo)
# Create an Instrument object
instrument = pretty_midi.Instrument(program=program_num, is_drum=is_drum)
# Set the piano roll to the Instrument object
set_piano_roll_to_instrument(piano_roll, instrument, velocity, tempo, beat_resolution)
# Add the instrument to the PrettyMIDI object
midi.instruments.append(instrument)
# Write out the MIDI data
midi.write(filename)
示例10: pianoroll_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def pianoroll_to_midi(pianoroll, midi_folder, filename, instrument_name, bpm):
if not os.path.exists(midi_folder):
os.makedirs(midi_folder)
midi = pm.PrettyMIDI(initial_tempo=bpm, resolution=200)
midi.time_signature_changes.append(pm.TimeSignature(4, 4, 0))
piano_program = pm.instrument_name_to_program(instrument_name)
piano = pm.Instrument(program=piano_program)
ind = np.nonzero(pianoroll)
for i in range(ind[0].shape[0]):
note = pm.Note(velocity=80, pitch=ind[1][i], start=(60/(2*bpm))*ind[0][i], end=(60/(2*bpm))*ind[0][i] + 0.25)
piano.notes.append(note)
midi.instruments.append(piano)
# print(midi.get_tempo_changes())
midi.write(midi_folder + filename+'.mid')
示例11: pianoroll_to_midi_continous
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def pianoroll_to_midi_continous(pianoroll, midi_folder, filename, instrument_name, bpm):
if not os.path.exists(midi_folder):
os.makedirs(midi_folder)
midi = pm.PrettyMIDI(initial_tempo=bpm, resolution=200)
midi.time_signature_changes.append(pm.TimeSignature(4, 4, 0))
piano_program = pm.instrument_name_to_program(instrument_name)
piano = pm.Instrument(program=piano_program)
tracker = []
start_times = dict()
for i, note_vector in enumerate(pianoroll):
notes = list(note_vector.nonzero()[0])
# print('notes',notes)
removal_list = []
for note in tracker:
if note in notes and (i)%8 is not 0:
# print('removing', note, 'from notes')
notes.remove(note)
else:
midi_note = pm.Note(velocity=80, pitch=note, start=(60/(2*bpm))*start_times[note], end=(60/(2*bpm))*i)
piano.notes.append(midi_note)
# print('removing', note, 'from tracker')
removal_list.append(note)
for note in removal_list:
tracker.remove(note)
# print('tracker',tracker)
# print('notes',notes)
for note in notes:
tracker.append(note)
start_times[note]=i
# print('tracker',tracker)
# print('-'*50)
midi.instruments.append(piano)
# print(midi.get_tempo_changes())
midi.write(midi_folder + filename+'.mid')
示例12: write_piano_roll_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def write_piano_roll_to_midi(piano_roll, filename, program_num=0, is_drum=False, velocity=100, tempo=120.0, beat_resolution=24):
# Create a PrettyMIDI object
midi = pretty_midi.PrettyMIDI(initial_tempo=tempo)
# Create an Instrument object
instrument = pretty_midi.Instrument(program=program_num, is_drum=is_drum)
# Set the piano roll to the Instrument object
set_piano_roll_to_instrument(piano_roll, instrument, velocity, tempo, beat_resolution)
# Add the instrument to the PrettyMIDI object
midi.instruments.append(instrument)
# Write out the MIDI data
midi.write(filename)
示例13: write_test_note
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def write_test_note(path, duration, note):
midi = pretty_midi.PrettyMIDI()
instrument = pretty_midi.Instrument(0)
instrument.notes.append(pretty_midi.Note(100, note, 0.0, duration))
midi.instruments.append(instrument)
midi.write(path)
示例14: save
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
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)
示例15: gen_frame_info_from_notes
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import Instrument [as 别名]
def gen_frame_info_from_notes(midi_notes, t_unit=0.02):
tmp_midi = pretty_midi.PrettyMIDI()
inst = pretty_midi.Instrument(program=0)
inst.notes += midi_notes
tmp_midi.instruments.append(inst)
piano_roll = tmp_midi.get_piano_roll(fs=round(1/t_unit)).transpose()
low = librosa.note_to_midi("A0")
hi = librosa.note_to_midi("C8")+1
piano_roll = piano_roll[:, low:hi]
return gen_frame_info(piano_roll, t_unit=t_unit)