craffel/pretty-midi

How to add tempo change events?

lucasnfe opened this issue · 1 comments

Hi,

How can I include tempo change events into new midi files created from notes? For example, in the following function:

def save_midi(notes, tempo_changes, path):
    # Create a PrettyMIDI object
    midi_data = pretty_midi.PrettyMIDI()

    # Create an Instrument instance for a piano instrument
    piano_program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano')
    piano = pretty_midi.Instrument(program=piano_program)

    # Add notes
    for n in notes:
        piano.notes.append(n)

   # Add tempo changes
   ...

    midi_data.instruments.append(piano)
    midi_data.write(path)

Is it possible to create a list of tempo changes (second argument) and add it to the new midi file?

Thanks!

Hi, it is technically possible but not advised because there is no enforcement that note timing matches the tempo grid's timing. If you want to modify the timing of the file, you can use pretty_midi.PrettyMIDI.adjust_times(). If you want to add tempo changes solely for annotation purposes (and you don't care whether the timing of the notes has anything to do with the tempo), you can manually modify pretty_midi.PrettyMIDI._tick_scales (note that this is a protected attribute because it is not recommended). You can look at https://github.com/craffel/pretty-midi/blob/master/pretty_midi/pretty_midi.py#L388 to see how the entries in that list of tuples is utilized. For example, to add a tempo change to 120 BPM at 0.5 seconds to the pretty_midi.PrettyMIDI object called "pm", you could do
pm._tick_scales.append((pm.time_to_tick(0.5), 60.0/(120*pm.resolution)))
or some such thing. If you modify _tick_scales, you may need to call pm._update_tick_to_time. Note again that this behavior is not supported.