Is there a way to determine the duration of an .mid file in python whether it be by examining the headers or by using an existing library?
Asked
Active
Viewed 1,788 times
3 Answers
5
I verified that the Mido library works great on several tricky Type 0 and Type 1 files. http://mido.readthedocs.org/en/latest/midi_files.html
from mido import MidiFile
mid = MidiFile('testfile.mid')
print(mid.length)

chadwackerman
- 804
- 12
- 9
0
Take a look at python-midi. I don't think it has a specific method that will tell immediately tell you what the duration is, but you should be able to calculate it based on the number of ticks and the tempo. Here's a rough example, but you'd have to play with the library a bit to see what the objects it gives you look like.
import midi
pattern = midi.read_midifile("mymidi.mid")
highest_tick = 0
for track in pattern:
for tick in track:
if tick['position'] > highest_tick:
highest_tick = tick['position']
# duration = some math of tick * tempo

Leah Sapan
- 3,621
- 7
- 33
- 57
-
Hmm, i took a look at this before asking the question, I do not believe this project has any methods to get those values needed to calculate the duration. – user784637 Jan 27 '14 at 01:54
-
I double checked the documentation and it appears like you should be able to, I added an example to give you an idea. – Leah Sapan Jan 27 '14 at 02:10
-
qwr suggested aubio.org, I'm not familiar with it but that may work better for you. Whichever library you use, the same idea applies. – Leah Sapan Jan 27 '14 at 02:12
-
The tempo can change during the song; you have to walk the whole file to calculate a duration. The Mido library offers a calculated length field. – chadwackerman Feb 08 '16 at 22:25