suppress the end of a midi file

257 views Asked by At

I want to remove the end of a midi file in order to have a file of 30 seconds for example.

I tried to compute on each track the total time value and to delete messages each time it is over 30 seconds. However, when I listen to it, it is still the same duration, the only difference is that there is a gap without sound in the middle of the file.

Does any one have an idea of how I can do it ?

Thank you!

1

There are 1 answers

1
AudioBubble On

Most likely, you forgot to remove some MetaMessages. Try this:

import mido

midifile = mido.MidiFile('old.mid')
lasttick = # last tick you want to keep

for track in midifile.tracks:
    tick = 0
    keep = []
    for msg in track:
        if tick > lasttick:
            break
        keep.append(msg)
        tick += msg.time
    track.clear()
    track.extend(keep)

midifile.save('new.mid')