How to Calculate Duration of a Note in Midi File Using Mido

39 Views Asked by At

for this program I am attempting to find attributes of a Midi file such as the frequency and duration of each note, and store them in a database (Sqlite3).

I have successfully been able to do the frequency part, however I can't seem to get the duration of each note to work.

import mido
import sqlite3

def midi_to_frequency(midi_note):
    return 440 * (2 ** ((midi_note - 69) / 12))

midi_file = "Queen.mid"

con = sqlite3.connect('SciFair.db')
cur = con.cursor()


cur.execute('''CREATE TABLE IF NOT EXISTS frequencies
             (id INTEGER PRIMARY KEY, frequency)''')

mid = mido.MidiFile(midi_file)

for msg in mid:
    if msg.type == 'note_on':
        frequency = midi_to_frequency(msg.note)
        cur.execute("INSERT INTO frequencies (frequency) VALUES (?)", (frequency,))
        print(frequency)
    
       
con.commit()
con.close()

I have tried using

msg.time

to find the duration of each note, however, the results haven't been the best. For example, when I try it sometimes the output comes out as "0" for the duration, which is not possible as it cannot be a note if it doesn't have any duration.

Also, to my very basic understanding of Mido, it uses Ticks and not seconds or any other type of normal metric. How would I convert these Ticks to seconds?

Any suggestions on how to do this?

0

There are 0 best solutions below