File size: 1,638 Bytes
d66db56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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()