How to "slow down" a MIDI file (ideally in Python)?

As Vinko says, you can edit the midifile, but since it's a binary format, squeezed into the least number of bits possible, it helps to have help.

This is a midi-to-text converter (and vice-versa):
http://midicomp.opensrc.org/
I've been using it quite a bit lately. it's pretty trivial to do text processing (e.g. searching for line with "Tempo") for simple operations once you have the midifile as text. haven't tried on mac (compiled with no problem on ubuntu 8.04).

Regarding midifile tempo specifically, it's really easy to slow down or speed up playback since the timing of events is specified in terms of "ticks", whose real duration in seconds is determined by the tempo parameter described in Vinko's quote. I believe time signature is not so relevant, and is mainly for displaying bars/beats correctly when opened in a midi sequencer.

Also, aside from pyPortMidi, there are a couple of other python midi modules around.

[hmmm... it seems i can only post on link per post, being a new user. i'll try posting the links to the python modules in a couple comments or another couple answers...]


You could edit the file, as per http://www.sonicspot.com/guide/midifiles.html

Although there probably is a MIDI reading/writing library already. In fact, it was a matter of seeing the related questions: Simple, Cross Platform MIDI Library for Python

Set Tempo

This meta event sets the sequence tempo in terms of microseconds per quarter-note which is encoded in three bytes. It usually is found in the first track chunk, time-aligned to occur at the same time as a MIDI clock message to promote more accurate synchronization. If no set tempo event is present, 120 beats per minute is assumed. The following formula's can be used to translate the tempo from microseconds per quarter-note to beats per minute and back.

MICROSECONDS_PER_MINUTE = 60000000

BPM = MICROSECONDS_PER_MINUTE / MPQN
MPQN = MICROSECONDS_PER_MINUTE / BPM
Meta Event  Type    Length  Microseconds/Quarter-Note
255 (0xFF)  81 (0x51)   3   0-8355711

You can use music21 to do this, though I have only tested it on OSX 10.10.1.

import music21

fctr = 1.25 # scale (in this case stretch) the overall tempo by this factor
score = music21.converter.parse('song.mid')
newscore = score.scaleOffsets(fctr).scaleDurations(fctr)

newscore.write('midi','song_slow.mid') 

Offsets are like the timestamps of each note, and durations is how long the note is sounded, I believe applying the same scale factor to each is kind of like adjusting the tempo.

If you are like me then you are listening to the same songs 7 years later and can give this a try! Otherwise, I hope this helps someone else who woke up today like me and was scratching my head trying to solve this problem easily.

Tags:

Python

Midi