Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def write_tempo_map(self):
# Figure out BPM, either from command line argument or from actual timing
bpm = self.tempo_bpm
if not bpm:
end_time = time.time()
delta = end_time - self.start_time
beats = self.total_ticks / TICKS_PER_BEAT
bpm = int(round(beats * 60 / delta))
print("BPM: %d" % bpm)
# Write tempo and time signature to tempo map track
self.tempo_map_track.append(mido.MetaMessage('set_tempo', tempo=mido.bpm2tempo(bpm)))
self.tempo_map_track.append(mido.MetaMessage('time_signature', numerator=4, denominator=4))
if 'seed' in request.args:
# TODO: This may not work for multithreading?
seed = int(request.args['seed'])
np.random.seed(seed)
print('Using seed {}'.format(seed))
uuid = uuid4()
logger.info('Stream ID: {}'.format(uuid))
logger.info('Style: {}'.format(gen_style))
folder = '/tmp'
mid_fname = os.path.join(folder, '{}.mid'.format(uuid))
logger.info('Generating MIDI')
seq = Generation(model, style=gen_style, default_temp=0.9).generate(seq_len=seq_len, show_progress=False)
track_builder = TrackBuilder(iter(seq), tempo=mido.bpm2tempo(90))
track_builder.run()
midi_file = track_builder.export()
midi_file.save(mid_fname)
logger.info('Synthesizing MIDI')
# Synthsize
fsynth_proc = subprocess.Popen([
'fluidsynth',
'-nl',
'-f', 'fluidsynth.cfg',
'-T', 'raw',
'-g', str(gain),
'-F', '-',
soundfont,
mid_fname
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:
print("\n***Warning: invalid key passed to MIDI renderer. Using C instead.\n")
track.append(mido.MetaMessage('key_signature', key='C'))
try:
track.append(mido.Message('program_change', program=self.midi_instrument, time=0))
except ValueError:
print("\n***Warning: invalid instrument passed to MIDI renderer. Using piano instead.\n")
track.append(mido.Message('program_change', program=1, time=0))
print("\n***WARNING: MIDI was not created because mido module was not found. ***\n")
return None
try:
self.midi_key = re.sub(r'#', '#m', song.get_music_key()) # For mido sharped keys are minor
except TypeError:
print("\n***Warning: Invalid music key passed to the MIDI renderer: using C instead\n")
self.midi_key = 'C'
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:
print("\n***Warning: invalid key passed to MIDI renderer. Using C instead.\n")
track.append(mido.MetaMessage('key_signature', key='C'))
try:
track.append(mido.Message('program_change', program=self.midi_instrument, time=0))
def tokens_to_midi(tokens):
"""
Takes an event sequence and encodes it into MIDI file
"""
midi_file = mido.MidiFile()
track = mido.MidiTrack()
tempo = mido.bpm2tempo(120)
track.append(mido.MetaMessage('set_tempo', tempo=tempo))
last_velocity = 0
delta_ticks = 0
for token in tokens:
if token == TOKEN_EOS:
pass
# Do nothing
elif token >= TOKEN_WAIT and token < TOKEN_NOTE:
delta_ticks += token - TOKEN_WAIT
elif token >= TOKEN_NOTE and token < TOKEN_VEL:
note = token - TOKEN_NOTE
ticks = int(round(mido.second2tick(delta_ticks / TICKS_PER_SEC, midi_file.ticks_per_beat, tempo)))
if last_velocity == 0:
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
total_frames = 0
while True:
samples, read = s()
new_note = notes_o(samples)
if (new_note[0] != 0):
note_str = ' '.join(["%.2f" % i for i in new_note])
def write_buffers(self, song):
global no_mido_module
if no_mido_module:
print("\n***WARNING: MIDI was not created because mido module was not found.")
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: