Last active
January 3, 2024 01:06
-
-
Save wsricardo/4cf8be8a907a79d88b5689d053f93fd7 to your computer and use it in GitHub Desktop.
Midi File With Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Created on Mon Jan 1 12:20:56 2024 | |
@author: wsricardo | |
Instagram: @dimensao.alfa | |
Blog: wsricardo.blogspot.com | |
""" | |
# Matrix (array) data type for sequence | |
song = [] | |
import mido | |
from pygame import mixer | |
""" | |
velocity - key pressed | |
time - time between notes | |
""" | |
mid = mido.MidiFile('song.mid', clip=True) | |
#print(mid.tracks) | |
def sseq( mid ): | |
seq = [] | |
for track in mid.tracks: | |
for msg in track: | |
seq.append( | |
msg | |
) | |
return seq | |
def sseqn( seq ): | |
""" | |
Parameters | |
---------- | |
seq : TYPE | |
Array with messages for note_on in midi file. | |
Returns | |
------- | |
l : TYPE | |
Array of notes with time duration and sleep time between notes.. | |
""" | |
l = [] | |
count = 0 | |
for note in seq: | |
current_time = note['time'] | |
current_note = note['note'] | |
if count % 2 == 0: | |
last_time = current_time | |
last_note = current_note | |
current_time = note['time'] | |
current_note = note['note'] | |
l.append( { | |
'note': current_note, | |
'time': last_time + current_time, | |
'time_sleep': last_time | |
} ) | |
count += 1 | |
return l | |
def sseqmk( mid ): | |
""" | |
Parameters | |
---------- | |
mid : midi | |
Midi object loaded with mido. | |
Returns | |
------- | |
seq : TYPE | |
Sequence for messages of mid object. | |
""" | |
seq = [] | |
for track in mid.tracks: | |
for msg in track: | |
if 'note' in msg.dict().keys(): | |
seq.append( { | |
'type': msg.dict()['type'], | |
'time': msg.dict()['time'], | |
'channel': msg.dict()['channel'], | |
'note': msg.dict()['note'], | |
'velocity': msg.dict()['velocity'] | |
} ) | |
return seq | |
#s = sseqmk( mid ) | |
print( sseqn( sseqmk( mid ) ) ) | |
#mixer.init() # initialization mixer for midi before play midi file | |
#mixer.music.load( mid.filename ) | |
#mixer.music.play() # play midi file loaded with mido in variable "mid" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment