import gradio as gr import mido import pygame import threading import time # Function to play MIDI def play_midi(file): pygame.midi.init() port = pygame.midi.Output(0) mid = mido.MidiFile(file.name) for msg in mid.play(): if msg.type == 'note_on': port.note_on(msg.note, msg.velocity) elif msg.type == 'note_off': port.note_off(msg.note, msg.velocity) port.close() pygame.midi.quit() # Function to visualize MIDI def visualize_midi(file): mid = mido.MidiFile(file.name) events = [] for track in mid.tracks: for msg in track: if msg.type in ['note_on', 'note_off']: events.append((msg.time, msg.type, msg.note, msg.velocity)) # Create a simple visualization (text-based for this example) visualization = "" current_time = 0 for event in events: current_time += event[0] visualization += f"Time: {current_time}, Type: {event[1]}, Note: {event[2]}, Velocity: {event[3]}\n" return visualization # Gradio interface def midi_interface(file): # Start playing MIDI in a separate thread to avoid blocking threading.Thread(target=play_midi, args=(file,)).start() # Return visualization visualization = visualize_midi(file) return visualization # Gradio blocks with gr.Blocks() as demo: midi_file = gr.File(label="Upload MIDI File") visualization_output = gr.Textbox(label="MIDI Visualization", lines=20) play_btn = gr.Button("Play MIDI and Visualize") play_btn.click(fn=midi_interface, inputs=midi_file, outputs=visualization_output) demo.launch()