django / backend /api /midi_utils.py
peter288's picture
Upload 11 files
d407cff verified
import mido
from io import BytesIO
def process_midi(midi_bytes: bytes) -> BytesIO:
"""
Processes a MIDI file by transposing all notes up by one semitone.
Args:
midi_bytes: The raw bytes of the input MIDI file.
Returns:
A BytesIO buffer containing the processed MIDI data.
"""
# Create an in-memory file-like object from the input bytes
with BytesIO(midi_bytes) as input_buffer:
mid = mido.MidiFile(file=input_buffer)
# Iterate over all tracks in the MIDI file
for i, track in enumerate(mid.tracks):
# Iterate over all messages in the track
for msg in track:
# Check if the message is a note_on or note_off event
if msg.type in ['note_on', 'note_off']:
# Transpose the note by +1 semitone
# We add a check to ensure the note doesn't go above 127
if msg.note < 127:
msg.note += 1
# Save the processed MIDI data to an in-memory output buffer
output_buffer = BytesIO()
mid.save(file=output_buffer)
# Reset the buffer's position to the beginning
output_buffer.seek(0)
return output_buffer