Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
win_s = 512 // downsample # fft size
hop_s = 256 // downsample # hop size
s = source(filename, samplerate, hop_s)
samplerate = s.samplerate
tolerance = 0.8
notes_o = notes("default", win_s, hop_s, samplerate)
print("%8s" % "time","[ start","vel","last ]")
# create a midi file
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
ticks_per_beat = mid.ticks_per_beat # default: 480
bpm = 120 # default midi tempo
tempo = bpm2tempo(bpm)
track.append(MetaMessage('set_tempo', tempo=tempo))
track.append(MetaMessage('time_signature', numerator=4, denominator=4))
def frames2tick(frames, samplerate=samplerate):
sec = frames / float(samplerate)
return int(second2tick(sec, ticks_per_beat, tempo))
last_time = 0
# total number of frames read
""" Extract data from midi file
Args:
Song: a song object containing the tracks and melody
filename (str): the path were to save the song
"""
midi_data = mido.MidiFile(ticks_per_beat=song.ticks_per_beat)
# Define track 0
new_track = mido.MidiTrack()
midi_data.tracks.append(new_track)
new_track.extend(song.tempo_map)
for i, track in enumerate(song.tracks):
# Define the track
new_track = mido.MidiTrack()
midi_data.tracks.append(new_track)
new_track.append(mido.Message('program_change', program=0, time=0)) # Played with standard piano
messages = []
for note in track.notes:
# Add all messages in absolute time
messages.append(mido.Message(
'note_on',
note=note.note,
velocity=64,
channel=i,
time=note.tick))
messages.append(mido.Message(
'note_off',
note=note.note,
velocity=64,
def write_song(song, filename):
""" Extract data from midi file
Args:
Song: a song object containing the tracks and melody
filename (str): the path were to save the song
"""
midi_data = mido.MidiFile(ticks_per_beat=song.ticks_per_beat)
# Define track 0
new_track = mido.MidiTrack()
midi_data.tracks.append(new_track)
new_track.extend(song.tempo_map)
for i, track in enumerate(song.tracks):
# Define the track
new_track = mido.MidiTrack()
midi_data.tracks.append(new_track)
new_track.append(mido.Message('program_change', program=0, time=0)) # Played with standard piano
messages = []
for note in track.notes:
# Add all messages in absolute time
messages.append(mido.Message(
'note_on',
note=note.note,
velocity=64,
def samples_to_midi(samples, file, ticks_per_beat=48, thresh=0.5):
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
track.append(Message('program_change', program=4))
mid.ticks_per_beat = ticks_per_beat
ticks_per_measure = 4 * ticks_per_beat
ticks_per_sample = ticks_per_measure / samples_per_measure
# note_on channel=1 note=44 velocity=127 time=816
# note_off channel=1 note=44 velocity=64 time=24
abs_time = 0
last_time = 0
for sample in samples:
for y in range(sample.shape[0]):
abs_time += ticks_per_sample
def multi_pianoroll_to_midi(file_name, bpm, pianoroll_dic):
# 1.初始化
mid = mido.MidiFile()
tracks = {} # 要保存的音轨信息
first_track = True
midi_tempo = round(60000000 / bpm) # 这首歌的速度(每一拍多少微秒)
# 2.保存音符
for key in pianoroll_dic:
# 2.1.定义音轨名称/使用乐器等
tracks[key] = mido.MidiTrack() # 定义新的音轨
mid.tracks.append(tracks[key]) # 在midi中添加这个音轨
if first_track:
tracks[key].append(mido.MetaMessage('set_tempo', tempo=midi_tempo, time=0)) # 设置歌曲的速度
first_track = False
tracks[key].append(mido.MetaMessage('track_name', name=pianoroll_dic[key]['name'], time=0)) # 这个音轨的名称
tracks[key].append(mido.Message('program_change', program=pianoroll_dic[key]['program'], time=0, channel=key)) # 这个音轨使用的乐器
# 2.2.从piano_dict中获取音符列表并转化为midi message的形式
note_list = []
for note_it in pianoroll_dic[key]['note']:
note_list.append(['on', note_it[0], note_it[1], note_it[2]])
note_list.append(['off', note_it[0] + note_it[3], note_it[1], note_it[2]])
note_list = sorted(note_list, key=lambda item: item[1]) # 按照音符的时间排序
# 2.3.往tracks中保存这些音符
current_note_time = 0
for note_it in note_list:
def convert_hex_file(infile, outfile):
midi_file = mido.MidiFile()
track = mido.MidiTrack()
midi_file.tracks.append(track)
line_num = 0
errors = 0
for line in infile:
line_num += 1
try:
msg = (mido.Message.from_hex(line.rstrip('\n')))
msg.time = 64
track.append(msg)
except ValueError:
# We don't want to stop when our ML algo makes nonsense
errors += 1
# print e.message
continue
def write_song(song, filename):
""" Save the song on disk
Args:
song (Song): a song object containing the tracks and melody
filename (str): the path were to save the song (don't add the file extension)
"""
midi_data = mido.MidiFile(ticks_per_beat=song.ticks_per_beat)
# Define track 0
new_track = mido.MidiTrack()
midi_data.tracks.append(new_track)
new_track.extend(song.tempo_map)
for i, track in enumerate(song.tracks):
# Define the track
new_track = mido.MidiTrack()
midi_data.tracks.append(new_track)
new_track.append(mido.Message('program_change', program=0, time=0)) # Played with standard piano
messages = []
for note in track.notes:
# Add all messages in absolute time
messages.append(mido.Message(
'note_on',
note=note.note,
velocity=64,
def write_midi(self):
global no_mido_module
if no_mido_module:
print("\n***WARNING: MIDI was not created because mido module was not found. ***\n")
return None
mid = mido.MidiFile(type=0)
track = mido.MidiTrack()
mid.tracks.append(track)
try:
tempo = mido.bpm2tempo(self.midi_bpm)
track.append(mido.MetaMessage('set_tempo', tempo=tempo))
except ValueError:
print("\n***Warning: invalid tempo passed to MIDI renderer. Using 120 bpm instead.\n")
tempo = mido.bpm2tempo(120)
track.append(mido.MetaMessage('set_tempo', tempo=tempo))
sec = mido.second2tick(1, ticks_per_beat=mid.ticks_per_beat, tempo=tempo) # 1 second in ticks
note_ticks = self.midi_note_duration * sec * 120 / self.midi_bpm # note duration in ticks
try:
track.append(mido.MetaMessage('key_signature', key=self.midi_key))
except ValueError:
return None
try:
self.midi_key = re.sub(r'#', '#m', song.get_music_key()) # For mido sharped keys are minor
except TypeError:
self.midi_key = Resources.DEFAULT_KEY
print(f"\n***ERROR: Invalid music key passed to the MIDI renderer: using {self.midi_key} instead.")
try:
tempo = mido.bpm2tempo(self.midi_bpm)
except ValueError:
print(f"\n***ERROR: invalid tempo passed to MIDI renderer. Using {Resources.DEFAULT_BPM} bpm instead.")
tempo = mido.bpm2tempo(Resources.DEFAULT_BPM)
mid = mido.MidiFile(type=0)
track = mido.MidiTrack()
mid.tracks.append(track)
sec = mido.second2tick(1, ticks_per_beat=mid.ticks_per_beat, tempo=tempo) # 1 second in ticks
note_ticks = self.midi_note_duration * sec * Resources.DEFAULT_BPM / self.midi_bpm # note duration in ticks
self.write_header(mid, track, tempo)
instrument_renderer = MidiInstrumentRenderer(self.locale)
song_lines = song.get_lines()
for line in song_lines:
if len(line) > 0:
if line[0].get_type().lower().strip() != 'voice':
instrument_index = 0
for instrument in line:
instrument.set_index(instrument_index)
#instrument_render = instrument.render_in_midi(note_duration=note_ticks,