Next commited on
Commit
d66db56
·
verified ·
1 Parent(s): bdbceb7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import mido
3
+ import pygame
4
+ import threading
5
+ import time
6
+
7
+ # Function to play MIDI
8
+ def play_midi(file):
9
+ pygame.midi.init()
10
+ port = pygame.midi.Output(0)
11
+ mid = mido.MidiFile(file.name)
12
+ for msg in mid.play():
13
+ if msg.type == 'note_on':
14
+ port.note_on(msg.note, msg.velocity)
15
+ elif msg.type == 'note_off':
16
+ port.note_off(msg.note, msg.velocity)
17
+ port.close()
18
+ pygame.midi.quit()
19
+
20
+ # Function to visualize MIDI
21
+ def visualize_midi(file):
22
+ mid = mido.MidiFile(file.name)
23
+ events = []
24
+ for track in mid.tracks:
25
+ for msg in track:
26
+ if msg.type in ['note_on', 'note_off']:
27
+ events.append((msg.time, msg.type, msg.note, msg.velocity))
28
+
29
+ # Create a simple visualization (text-based for this example)
30
+ visualization = ""
31
+ current_time = 0
32
+ for event in events:
33
+ current_time += event[0]
34
+ visualization += f"Time: {current_time}, Type: {event[1]}, Note: {event[2]}, Velocity: {event[3]}\n"
35
+ return visualization
36
+
37
+ # Gradio interface
38
+ def midi_interface(file):
39
+ # Start playing MIDI in a separate thread to avoid blocking
40
+ threading.Thread(target=play_midi, args=(file,)).start()
41
+
42
+ # Return visualization
43
+ visualization = visualize_midi(file)
44
+ return visualization
45
+
46
+ # Gradio blocks
47
+ with gr.Blocks() as demo:
48
+ midi_file = gr.File(label="Upload MIDI File")
49
+ visualization_output = gr.Textbox(label="MIDI Visualization", lines=20)
50
+ play_btn = gr.Button("Play MIDI and Visualize")
51
+
52
+ play_btn.click(fn=midi_interface, inputs=midi_file, outputs=visualization_output)
53
+
54
+ demo.launch()