本文整理汇总了Python中pretty_midi.PrettyMIDI方法的典型用法代码示例。如果您正苦于以下问题:Python pretty_midi.PrettyMIDI方法的具体用法?Python pretty_midi.PrettyMIDI怎么用?Python pretty_midi.PrettyMIDI使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pretty_midi
的用法示例。
在下文中一共展示了pretty_midi.PrettyMIDI方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: extract
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def extract(self, file_path, is_drum=False):
'''
Extract MIDI file.
Args:
file_path: File path of MIDI.
is_drum: Extract drum data or not.
Returns:
pd.DataFrame(columns=["program", "start", "end", "pitch", "velocity", "duration"])
'''
midi_data = pretty_midi.PrettyMIDI(file_path)
note_tuple_list = []
for instrument in midi_data.instruments:
if (is_drum is False and instrument.is_drum is False) or (is_drum is True and instrument.is_drum is True):
for note in instrument.notes:
note_tuple_list.append((instrument.program, note.start, note.end, note.pitch, note.velocity))
note_df = pd.DataFrame(note_tuple_list, columns=["program", "start", "end", "pitch", "velocity"])
note_df = note_df.sort_values(by=["program", "start", "end"])
note_df["duration"] = note_df.end - note_df.start
return note_df
示例2: converter
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def converter(filepath, src, dst):
"""Convert a MIDI file to a multi-track piano-roll and save the
resulting multi-track piano-roll to the destination directory. Return a
tuple of `midi_md5` and useful information extracted from the MIDI file.
"""
try:
midi_md5 = os.path.splitext(os.path.basename(filepath))[0]
multitrack = Multitrack(beat_resolution=CONFIG['beat_resolution'],
name=midi_md5)
pm = pretty_midi.PrettyMIDI(filepath)
multitrack.parse_pretty_midi(pm)
midi_info = get_midi_info(pm)
result_dir = change_prefix(os.path.dirname(filepath), src, dst)
make_sure_path_exists(result_dir)
multitrack.save(os.path.join(result_dir, midi_md5 + '.npz'))
return (midi_md5, midi_info)
except:
return None
示例3: decode_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [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
示例4: get_instr_pianoroll
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def get_instr_pianoroll(self, midi_instr, requested_shape):
"""Returns midi_instr as 2D (time, model pitch_range) pianoroll."""
pianoroll = np.zeros(requested_shape[1:-1])
if not midi_instr.notes:
return pianoroll
midi = pretty_midi.PrettyMIDI()
midi.instruments.append(midi_instr)
# TODO(annahuang): Sampling frequency is dataset dependent.
fs = 4
# Returns matrix of shape (128, time) with summed velocities.
roll = midi.get_piano_roll(fs=fs)
roll = np.where(roll > 0, 1, 0)
roll = roll.T
out_of_range_pitch_count = (
np.sum(roll[:, self.max_pitch + 1:]) + np.sum(roll[:, :self.min_pitch]))
if out_of_range_pitch_count > 0:
raise ValueError(
'%d pitches out of the range (%d, %d) the model was trained on.' %
(out_of_range_pitch_count, self.min_pitch, self.max_pitch))
roll = roll[:, self.min_pitch:self.max_pitch + 1]
return roll
示例5: load_notes
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def load_notes(midi_path, midi=None):
"""Load note data from the midi file.
Args:
midi_path (str): path to midi file
midi (pretty_midi.PrettyMIDI): pre-loaded midi object or None
if None, the midi object is loaded using midi_path
Returns:
note_data (NoteData)
"""
if midi is None:
midi = load_midi(midi_path)
intervals = []
pitches = []
confidence = []
for note in midi.instruments[0].notes:
intervals.append([note.start, note.end])
pitches.append(librosa.midi_to_hz(note.pitch))
confidence.append(note.velocity)
return utils.NoteData(np.array(intervals), np.array(pitches), np.array(confidence))
示例6: load_drum_events
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def load_drum_events(midi_path, midi=None):
"""Load drum events from the midi file.
Args:
midi_path (str): path to midi file
midi (pretty_midi.PrettyMIDI): pre-loaded midi object or None
if None, the midi object is loaded using midi_path
Returns:
drum_events (EventData)
"""
if midi is None:
midi = load_midi(midi_path)
start_times = []
end_times = []
events = []
for note in midi.instruments[0].notes:
start_times.append(note.start)
end_times.append(note.end)
events.append(DRUM_MAPPING[note.pitch])
return utils.EventData(np.array(start_times), np.array(end_times), np.array(events))
示例7: write_piano_rolls_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [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)
示例8: get_midi_info
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def get_midi_info(pm):
"""Return useful information from a pretty_midi.PrettyMIDI instance"""
if pm.time_signature_changes:
pm.time_signature_changes.sort(key=lambda x: x.time)
first_beat_time = pm.time_signature_changes[0].time
else:
first_beat_time = pm.estimate_beat_start()
tc_times, tempi = pm.get_tempo_changes()
if len(pm.time_signature_changes) == 1:
time_sign = '{}/{}'.format(pm.time_signature_changes[0].numerator,
pm.time_signature_changes[0].denominator)
else:
time_sign = None
midi_info = {
'first_beat_time': first_beat_time,
'num_time_signature_change': len(pm.time_signature_changes),
'time_signature': time_sign,
'tempo': tempi[0] if len(tc_times) == 1 else None
}
return midi_info
示例9: converter
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def converter(filepath):
"""Save a multi-track piano-roll converted from a MIDI file to target
dataset directory and update MIDI information to `midi_dict`"""
try:
midi_name = os.path.splitext(os.path.basename(filepath))[0]
multitrack = Multitrack(beat_resolution=24, name=midi_name)
pm = pretty_midi.PrettyMIDI(filepath)
midi_info = get_midi_info(pm)
multitrack.parse_pretty_midi(pm)
merged = get_merged(multitrack)
make_sure_path_exists(converter_path)
merged.save(os.path.join(converter_path, midi_name + '.npz'))
return [midi_name, midi_info]
except:
return None
示例10: create_tempo_histogram
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def create_tempo_histogram(data_path):
invalid_midi_files = np.chararray([])
exception_str_arr= np.chararray([])
tempo_array = np.array([])
filenames = os.listdir(data_path)
num_files = len(filenames)
for i, filename in enumerate(filenames):
print('file ', i, 'of ', num_files)
try:
tempo = pm.PrettyMIDI(data_path + filename).estimate_tempo()
tempo_array = np.append(tempo_array, tempo)
except (ValueError, EOFError, IndexError, OSError, KeyError, ZeroDivisionError) as e:
exception_str = 'Unexpected error in ' + filename + ':\n', e, sys.exc_info()[0]
print(exception_str)
invalid_midi_files = np.append(invalid_midi_files, filename)
exception_str_arr = np.append(exception_str_arr, exception_str)
tempo_histogram = np.histogram(tempo_array)
return tempo_histogram, invalid_midi_files, exception_str_arr
示例11: write_piano_rolls_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [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)
示例12: piano_roll_to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [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
示例13: to_midi
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [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
示例14: process
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def process(msd_id: str, counter: AtomicCounter) -> Optional[dict]:
"""
Processes the given MSD id and increments the counter. The
method will call the extract_pianos method and write the resulting MIDI
files to disk.
:param msd_id: the MSD id to process
:param counter: the counter to increment
:return: the dictionary containing the MSD id and the PrettyMIDI pianos,
raises an exception if the file cannot be processed
"""
try:
with tables.open_file(msd_id_to_h5(msd_id, args.path_dataset_dir)) as h5:
pm_pianos = extract_pianos(msd_id)
for index, pm_piano in enumerate(pm_pianos):
pm_piano.write(os.path.join(args.path_output_dir,
f"{msd_id}_{index}.mid"))
return {"msd_id": msd_id, "pm_pianos": pm_pianos}
except Exception as e:
print(f"Exception during processing of {msd_id}: {e}")
finally:
counter.increment()
开发者ID:PacktPublishing,项目名称:hands-on-music-generation-with-magenta,代码行数:24,代码来源:chapter_06_example_06.py
示例15: test_create_midi_from_piece
# 需要导入模块: import pretty_midi [as 别名]
# 或者: from pretty_midi import PrettyMIDI [as 别名]
def test_create_midi_from_piece(
path_to_tmp_file: str, piece: Piece, all_steps: List[Tuple[int, int]],
instrument_number: int, note_number: int, expected: Dict[str, float]
) -> None:
"""Test `create_midi_from_piece` function."""
for movement, duration in all_steps:
piece.add_line_element(movement, duration)
create_midi_from_piece(
piece,
path_to_tmp_file,
measure_in_seconds=1,
cantus_firmus_instrument=0,
counterpoint_instrument=0,
velocity=100
)
midi_data = pretty_midi.PrettyMIDI(path_to_tmp_file)
instrument = midi_data.instruments[instrument_number]
midi_note = instrument.notes[note_number]
result = {
'pitch': midi_note.pitch,
'start': midi_note.start,
'end': midi_note.end
}
assert result == expected