Spaces:
Sleeping
Sleeping
File size: 6,932 Bytes
3aa7092 | 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | import gradio as gr
from fastapi import FastAPI, Request
import json
# THIS VERSION WORKS
# AND SENDS BACK A NOTE A FIFTH HIGHER THAN THE INPUT NOT ON THE SELECTED PORT
#
# ✅ Create FastAPI App
app = FastAPI()
# ✅ MIDI Processing Function in Python
@app.post("/midi_input")
async def process_midi(request: Request):
try:
midi_data = await request.json()
note = midi_data["note"]
velocity = midi_data["velocity"]
print(f"🎹 Received MIDI Note: {note}, Velocity: {velocity}")
# 🚀 Process MIDI data (example: Transpose + Generate New Notes)
generated_note = (note + 5) % 128 # Transpose up by 3 semitones
generated_velocity = min(velocity + 10, 127) # Increase velocity slightly
# ✅ Send MIDI Response Back to Client
return {
"status": "success",
"generated_note": generated_note,
"generated_velocity": generated_velocity,
"original_note": note
}
except Exception as e:
print(f"🚨 Error processing MIDI: {str(e)}")
return {"status": "error", "message": str(e)}
# ✅ JavaScript to Capture and Send MIDI Data
midi_js = """
<script>
let midiAccess = null;
let selectedInput = null;
let selectedOutput = null;
// ✅ Request MIDI Access
navigator.requestMIDIAccess()
.then(access => {
console.log("✅ MIDI Access Granted!");
midiAccess = access;
updateMIDIDevices();
midiAccess.onstatechange = updateMIDIDevices;
})
.catch(err => console.error("🚨 MIDI API Error:", err));
// ✅ Update MIDI Input & Output Menus
function updateMIDIDevices() {
let inputSelect = document.getElementById("midiInput");
let outputSelect = document.getElementById("midiOutput");
if (!inputSelect || !outputSelect) {
console.error("❌ MIDI dropdowns not found!");
return;
}
// Clear existing options
inputSelect.innerHTML = '<option value="">Select MIDI Input</option>';
outputSelect.innerHTML = '<option value="">Select MIDI Output</option>';
// Populate MIDI Input Devices
midiAccess.inputs.forEach((input, key) => {
let option = document.createElement("option");
option.value = key;
option.textContent = input.name || `MIDI Input ${key}`;
inputSelect.appendChild(option);
});
// Populate MIDI Output Devices
midiAccess.outputs.forEach((output, key) => {
let option = document.createElement("option");
option.value = key;
option.textContent = output.name || `MIDI Output ${key}`;
outputSelect.appendChild(option);
});
console.log("🎛 Updated MIDI Input & Output devices.");
}
// ✅ Handle MIDI Input Selection
function selectMIDIInput() {
let inputSelect = document.getElementById("midiInput");
let inputId = inputSelect.value;
if (selectedInput) {
selectedInput.onmidimessage = null;
}
if (midiAccess.inputs.has(inputId)) {
selectedInput = midiAccess.inputs.get(inputId);
selectedInput.onmidimessage = handleMIDIMessage;
console.log(`🎤 MIDI Input Selected: ${selectedInput.name}`);
}
}
// ✅ Handle MIDI Output Selection
function selectMIDIOutput() {
let outputSelect = document.getElementById("midiOutput");
let outputId = outputSelect.value;
if (midiAccess.outputs.has(outputId)) {
selectedOutput = midiAccess.outputs.get(outputId);
console.log(`🎹 MIDI Output Selected: ${selectedOutput.name}`);
}
}
// ✅ Play a MIDI Note Sent Back from Python
function playMIDINote(note, velocity) {
if (!selectedOutput) {
console.warn("⚠️ No MIDI output selected.");
return;
}
let noteOnMessage = [0x90, note, velocity]; // Note On
let noteOffMessage = [0x80, note, 0]; // Note Off
console.log(`🎵 Playing Generated MIDI Note ${note}, Velocity ${velocity}`);
try {
selectedOutput.send(noteOnMessage);
setTimeout(() => {
selectedOutput.send(noteOffMessage);
console.log(`🔇 Note Off ${note}`);
}, 500);
} catch (error) {
console.error("🚨 Error playing MIDI note:", error);
}
}
// ✅ Send MIDI Data to Python
// ✅ Handle Incoming MIDI Messages and Send to Python
function handleMIDIMessage(event) {
let originalNote = event.data[1];
let velocity = event.data[2];
let midiData = {
note: originalNote,
velocity: velocity
};
console.log(`🎤 MIDI Input: Note ${originalNote}, Velocity ${velocity}`);
// ✅ Send MIDI data to Python backend
fetch("/midi_input", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(midiData)
})
.then(response => response.json())
.then(data => {
console.log("📨 MIDI sent to Python. Response:", data);
// ✅ Play the generated MIDI response
if (data.status === "success") {
playMIDINote(data.generated_note, data.generated_velocity);
}
})
.catch(error => console.error("🚨 Error sending MIDI data:", error));
}
// ✅ Attach Generate Button Event
function attachButtonEvent() {
let generateButton = document.getElementById("generateButton");
if (generateButton) {
console.log("✅ Generate button found! Attaching event listener...");
generateButton.addEventListener("click", function () {
console.log("🎹 Generate button clicked.");
if (!selectedOutput) {
alert("⚠️ Please select a MIDI Output first!");
return;
}
let randomNote = 60 + Math.floor(Math.random() * 12); // Random note from C4 to B4
console.log(`🎵 Generating MIDI Note: ${randomNote}`);
playMIDINote(randomNote, 100);
});
} else {
console.log("⏳ Waiting for button to be available...");
setTimeout(attachButtonEvent, 500); // Try again in 500ms
}
}
// ✅ Ensure the Button and Menus Are Loaded
window.onload = function() {
console.log("✅ Page fully loaded. Checking for elements...");
updateMIDIDevices();
attachButtonEvent();
};
</script>
<!-- 🎛 MIDI Input & Output Selection -->
<div>
<label for="midiInput">MIDI Input: </label>
<select id="midiInput" onchange="selectMIDIInput()"></select>
<label for="midiOutput">MIDI Output: </label>
<select id="midiOutput" onchange="selectMIDIOutput()"></select>
</div>
<!-- 🎶 "Generate MIDI" Button -->
<button id="generateButton">🎵 Generate MIDI Note</button>
"""
# ✅ Inject JavaScript and HTML
with gr.Blocks() as demo:
gr.HTML(midi_js)
# ✅ Mount FastAPI with Gradio
app = gr.mount_gradio_app(app, demo, path="/")
# ✅ Run the app
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860) |