Spaces:
Running
Running
File size: 24,677 Bytes
2e10f13 0760416 2e10f13 0760416 2e10f13 854715f 2e10f13 854715f 2e10f13 854715f 3a7d263 854715f 2e10f13 6e183e2 2e10f13 1683abe 79fb0a9 0760416 2e10f13 0760416 a31f0ea 2e10f13 854715f 13c1a17 854715f 2e10f13 854715f 2e10f13 13c1a17 2e10f13 1683abe 8c3f5b9 1683abe 79fb0a9 0760416 fd0e4cf 79fb0a9 1683abe 2e10f13 1e4259e 79fb0a9 1e4259e 854715f 1e4259e 3a7d263 1e4259e 3a7d263 1e4259e 854715f 1e4259e 854715f 1e4259e 854715f 1e4259e 6e183e2 854715f 1e4259e 854715f 1e4259e 6e183e2 2e10f13 1e4259e 2e10f13 1e4259e 2e10f13 1e4259e 2e10f13 1e4259e 571caf6 1e4259e 571caf6 1e4259e 571caf6 1e4259e 571caf6 8d34246 1e4259e 8d34246 1e4259e 2e10f13 1e4259e 0760416 1e4259e 0760416 1e4259e 0760416 1e4259e fd0e4cf 1e4259e fd0e4cf 1e4259e 0760416 1e4259e 0760416 1e4259e 0760416 1e4259e 0760416 1e4259e fd0e4cf 1e4259e fd0e4cf 1e4259e 2e10f13 1e4259e 1683abe 2e10f13 | 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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 | <!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Аудио в Ноты (Партитура)</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto; padding: 20px; background: #f9f9f9; color: #333; }
.container { background: white; padding: 25px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
h1 { font-size: 24px; text-align: center; }
p { font-size: 14px; color: #666; text-align: center; }
.upload-area { border: 2px dashed #ccc; border-radius: 8px; padding: 20px; text-align: center; margin: 20px 0; background: #fafafa; }
input[type="file"] { display: none; }
.custom-file-upload { display: inline-block; padding: 10px 20px; background: #007bff; color: white; border-radius: 6px; cursor: pointer; font-weight: bold; margin-bottom: 10px; }
.custom-file-upload:hover { background: #0056b3; }
#recordBtn { display: inline-block; padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; margin-left: 10px; }
#recordBtn:hover { background: #5a6268; }
#fileName { margin-top: 10px; font-size: 14px; color: #333; font-weight: bold; }
#recordStatus { display: block; font-size: 13px; color: #dc3545; margin-top: 5px; min-height: 18px; }
#analyzeBtn { display: block; width: 100%; padding: 12px; background: #28a745; color: white; border: none; border-radius: 6px; font-size: 16px; font-weight: bold; cursor: pointer; margin-top: 15px; }
#analyzeBtn:disabled { background: #6c757d; cursor: not-allowed; }
#status { margin-top: 15px; font-size: 14px; color: #ff9800; text-align: center; min-height: 20px; word-wrap: break-word; }
.error-text { color: #dc3545 !important; font-weight: bold; font-size: 13px; background: #f8d7da; padding: 10px; border-radius: 5px; }
#result { display: none; margin-top: 20px; padding: 15px; background: #e9ecef; border-radius: 8px; text-align: center; }
.btn-group { display: flex; gap: 10px; justify-content: center; margin-bottom: 15px; flex-wrap: wrap; }
.download-btn { display: inline-block; padding: 10px 20px; color: white; text-decoration: none; border-radius: 6px; font-weight: bold; border: none; cursor: pointer; }
#downloadLink { background: #17a2b8; }
#downloadTxtBtn { background: #ff9800; }
#textResult { text-align: left; background: #fff; padding: 15px; border-radius: 6px; max-height: 150px; overflow-y: auto; font-size: 13px; font-family: monospace; border: 1px solid #ccc; margin: 0; white-space: pre-wrap; }
#sheetMusic { background: #fff; border-radius: 6px; padding: 15px; margin-top: 15px; overflow-x: auto; border: 1px solid #ccc; min-height: 150px; }
</style>
</head>
<body>
<div class="container">
<h1>🎵 Аудио в Ноты (Партитура)</h1>
<p>Загрузи файл или запиши мелодию. Программа создаст MIDI, текст и партитуру.</p>
<div class="upload-area">
<label for="audioFile" class="custom-file-upload">Выбрать файл</label>
<input type="file" id="audioFile" accept="audio/*">
<button type="button" id="recordBtn">🎤 Записать с микрофона</button>
<div id="fileName">Файл не выбран</div>
<div id="recordStatus"></div>
</div>
<button type="button" id="analyzeBtn">Анализировать аудио</button>
<div id="status"></div>
<div id="result">
<h3>Готово! 🎉</h3>
<div class="btn-group">
<a id="downloadLink" class="download-btn" href="#" download="melody.mid">Скачать MIDI</a>
<button type="button" id="downloadTxtBtn" class="download-btn">Скачать текст (.txt)</button>
</div>
<h4 style="margin-top: 15px; text-align: left; font-size: 15px;">Партитура:</h4>
<div id="sheetMusic">Здесь появится партитура...</div>
<h4 style="margin-top: 15px; text-align: left; font-size: 15px;">Распознанные ноты (текст):</h4>
<pre id="textResult"></pre>
</div>
</div>
<script>
// Ждем полной загрузки страницы
document.addEventListener('DOMContentLoaded', function() {
const fileInput = document.getElementById('audioFile');
const fileNameDisplay = document.getElementById('fileName');
const analyzeBtn = document.getElementById('analyzeBtn');
const statusDiv = document.getElementById('status');
const resultDiv = document.getElementById('result');
const downloadLink = document.getElementById('downloadLink');
const textResultDiv = document.getElementById('textResult');
const downloadTxtBtn = document.getElementById('downloadTxtBtn');
const recordBtn = document.getElementById('recordBtn');
const recordStatus = document.getElementById('recordStatus');
const sheetMusicDiv = document.getElementById('sheetMusic');
let currentFile = null;
let mediaRecorder;
let audioChunks = [];
let currentTextOutput = "";
function midiToAbcNote(midi) {
if (isNaN(midi)) midi = 60;
const notes = ['C', '^C', 'D', '^D', 'E', 'F', '^F', 'G', '^G', 'A', '^A', 'B'];
const safeMidi = Math.max(0, Math.min(127, midi));
const octave = Math.floor(safeMidi / 12) - 1;
let note = notes[safeMidi % 12];
if (octave === 4) return note;
if (octave === 5) return note.toLowerCase();
if (octave === 3) return note + ',';
if (octave === 6) return note.toLowerCase() + "'";
if (octave === 2) return note + ',,';
if (octave === 1) return note + ',,,';
return note;
}
function midiToNoteName(midi) {
if (isNaN(midi)) midi = 60;
const notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
const safeMidi = Math.max(0, Math.min(127, midi));
const octave = Math.floor(safeMidi / 12) - 1;
return notes[safeMidi % 12] + octave;
}
// --- Кнопка выбора файла ---
fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
currentFile = e.target.files[0];
fileNameDisplay.textContent = currentFile.name;
recordStatus.textContent = '';
resultDiv.style.display = 'none';
statusDiv.textContent = '';
statusDiv.className = '';
}
});
// --- Кнопка записи с микрофона ---
recordBtn.addEventListener('click', async () => {
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
return;
}
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
recordStatus.textContent = "Ваш браузер не поддерживает запись или вы открыли сайт без HTTPS.";
return;
}
try {
recordStatus.textContent = "Запрос доступа к микрофону...";
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
let options = {};
if (MediaRecorder.isTypeSupported('audio/webm')) options = { mimeType: 'audio/webm' };
else if (MediaRecorder.isTypeSupported('audio/mp4')) options = { mimeType: 'audio/mp4' };
mediaRecorder = new MediaRecorder(stream, options);
audioChunks = [];
mediaRecorder.ondataavailable = event => {
if (event.data.size > 0) audioChunks.push(event.data);
};
mediaRecorder.onstop = () => {
const mimeType = mediaRecorder.mimeType || 'audio/webm';
const audioBlob = new Blob(audioChunks, { type: mimeType });
const extension = mimeType.includes('mp4') ? 'mp4' : 'webm';
currentFile = new File([audioBlob], `Запись_с_микрофона.${extension}`, { type: audioBlob.type });
fileNameDisplay.textContent = "Запись готова к анализу";
recordStatus.textContent = "";
recordBtn.textContent = "🎤 Записать с микрофона";
recordBtn.style.background = "#6c757d";
resultDiv.style.display = 'none';
statusDiv.textContent = 'Нажмите "Анализировать аудио".';
statusDiv.className = '';
stream.getTracks().forEach(track => track.stop());
};
mediaRecorder.start();
recordBtn.textContent = "🛑 Остановить запись";
recordBtn.style.background = "#dc3545";
recordStatus.textContent = "Идет запись... Спойте или сыграйте мелодию!";
recordStatus.style.color = "#28a745";
fileNameDisplay.textContent = "";
statusDiv.textContent = "";
statusDiv.className = '';
} catch (err) {
console.error("Ошибка доступа к микрофону:", err);
recordStatus.textContent = "Ошибка микрофона: " + err.message;
recordStatus.style.color = "#dc3545";
}
});
// --- Вспомогательная функция для аудио ---
async function decodeAndResample(file) {
try {
const arrayBuffer = await file.arrayBuffer();
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const decoded = await audioCtx.decodeAudioData(arrayBuffer);
await audioCtx.close();
const sampleRate = 22050;
const offlineCtx = new OfflineAudioContext(1, Math.max(1, Math.ceil(decoded.duration * sampleRate)), sampleRate);
const source = offlineCtx.createBufferSource();
source.buffer = decoded;
source.connect(offlineCtx.destination);
source.start();
const rendered = await offlineCtx.startRendering();
return Float32Array.from(rendered.getChannelData(0));
} catch (e) {
throw new Error("Ошибка чтения аудио. Возможно, формат файла не поддерживается. (" + e.message + ")");
}
}
// --- Кнопка Анализа ---
analyzeBtn.addEventListener('click', async () => {
if (!currentFile) {
statusDiv.textContent = 'Сначала выберите файл или запишите звук.';
return;
}
analyzeBtn.disabled = true;
resultDiv.style.display = 'none';
statusDiv.className = '';
statusDiv.textContent = 'Шаг 1/3: Загрузка библиотек (это займет пару секунд)...';
try {
// Динамически подгружаем библиотеки, чтобы не вешать сайт
const basicPitchModule = await import('https://esm.sh/@spotify/basic-pitch@1.0.1');
const midiModule = await import('https://esm.sh/@tonejs/midi@2.0.28');
const BasicPitch = basicPitchModule.BasicPitch;
const noteFramesToTime = basicPitchModule.noteFramesToTime;
const outputToNotesPoly = basicPitchModule.outputToNotesPoly;
const Midi = midiModule.Midi;
const modelURL = 'https://unpkg.com/@spotify/basic-pitch@1.0.1/model/model.json';
const basicPitch = new BasicPitch(modelURL);
statusDiv.textContent = 'Шаг 2/3: Обработка аудио...';
let pcm = await decodeAndResample(currentFile);
let maxAmp = 0;
for (let i = 0; i < pcm.length; i++) {
maxAmp = Math.max(maxAmp, Math.abs(pcm[i]));
}
if (maxAmp < 0.01) {
throw new Error("Аудио слишком тихое (почти полная тишина). Проверьте микрофон.");
}
if (maxAmp < 0.9) {
for (let i = 0; i < pcm.length; i++) {
pcm[i] = (pcm[i] / maxAmp) * 0.95;
}
}
statusDiv.textContent = 'Шаг 3/3: Распознавание нот...';
const frames = [];
const onsets = [];
await basicPitch.evaluateModel(
pcm,
(f, o) => {
for (let i = 0; i < f.length; i++) frames.push(f[i]);
for (let i = 0; i < o.length; i++) onsets.push(o[i]);
},
(progress) => { statusDiv.textContent = `Распознавание... ${Math.round(progress * 100)}%`; }
);
const minFrames = Math.max(1, Math.round(0.120 * (22050 / 256)));
let rawNoteEvents = noteFramesToTime(
outputToNotesPoly(frames, onsets, 0.5, 0.3, minFrames)
);
const filteredNotes = [];
const lastPitchTime = {};
rawNoteEvents.sort((a, b) => a.startTimeSeconds - b.startTimeSeconds);
rawNoteEvents.forEach(note => {
const pitch = note.pitchMidi;
const start = note.startTimeSeconds;
if (lastPitchTime[pitch] === undefined || (start - lastPitchTime[pitch]) > 0.25) {
lastPitchTime[pitch] = start;
filteredNotes.push(note);
}
});
if (filteredNotes.length === 0) {
throw new Error("Модель не нашла музыкальных нот. Убедитесь, что вы поете/играете ОДНУ мелодию.");
}
// --- ГЕНЕРАЦИЯ ПАРТИТУРЫ ---
const BPM = 120;
const SECONDS_PER_BEAT = 60 / BPM;
let abcString = "X:1\nT:Распознанная мелодия\nM:4/4\nL:1/4\nK:C\n";
const groupedNotes = [];
let currentGroup = [];
filteredNotes.forEach(note => {
if (currentGroup.length === 0) {
currentGroup.push(note);
} else {
const lastNote = currentGroup[currentGroup.length - 1];
if (Math.abs(note.startTimeSeconds - lastNote.startTimeSeconds) < 0.08) {
currentGroup.push(note);
} else {
groupedNotes.push(currentGroup);
currentGroup = [note];
}
}
});
if (currentGroup.length > 0) groupedNotes.push(currentGroup);
let currentBeat = 0;
let barString = "";
let barBeatCount = 0;
groupedNotes.forEach((group, index) => {
const firstNote = group[0];
const startBeat = firstNote.startTimeSeconds / SECONDS_PER_BEAT;
const durationBeats = firstNote.durationSeconds / SECONDS_PER_BEAT;
const quantizedStart = Math.round(startBeat * 4) / 4;
let quantizedDuration = Math.max(0.25, Math.round(durationBeats * 4) / 4);
if (quantizedStart > currentBeat) {
let restDuration = quantizedStart - currentBeat;
while (restDuration > 0) {
if (restDuration >= 1) {
barString += "z ";
restDuration -= 1;
barBeatCount += 1;
} else if (restDuration >= 0.5) {
barString += "z/2 ";
restDuration -= 0.5;
barBeatCount += 0.5;
} else {
barString += "z/4 ";
restDuration -= 0.25;
barBeatCount += 0.25;
}
if (barBeatCount >= 4) {
abcString += barString + "| ";
barString = "";
barBeatCount = 0;
}
}
currentBeat = quantizedStart;
}
let noteStr = "";
if (group.length > 1) {
noteStr = "[" + group.map(n => midiToAbcNote(n.pitchMidi)).join("") + "]";
} else {
noteStr = midiToAbcNote(firstNote.pitchMidi);
}
let durationStr = "";
if (quantizedDuration === 0.25) durationStr = "/4";
else if (quantizedDuration === 0.5) durationStr = "/2";
else if (quantizedDuration === 1.5) durationStr = "3/2";
else if (quantizedDuration === 2) durationStr = "2";
else if (quantizedDuration === 3) durationStr = "3";
else if (quantizedDuration >= 4) { quantizedDuration = 4; durationStr = "4"; }
barString += noteStr + durationStr + " ";
currentBeat += quantizedDuration;
barBeatCount += quantizedDuration;
while (barBeatCount >= 4) {
abcString += barString + "| ";
barString = "";
barBeatCount -= 4;
}
});
if (barString.trim() !== "") {
while (barBeatCount < 4) {
if (4 - barBeatCount >= 1) {
barString += "z ";
barBeatCount += 1;
} else if (4 - barBeatCount >= 0.5) {
barString += "z/2 ";
barBeatCount += 0.5;
} else {
barString += "z/4 ";
barBeatCount += 0.25;
}
}
abcString += barString + "| ";
}
// 1. MIDI
const midi = new Midi();
const track = midi.addTrack();
filteredNotes.forEach(note => {
track.addNote({
midi: note.pitchMidi,
time: note.startTimeSeconds,
duration: note.durationSeconds,
velocity: 0.8
});
});
const midiBytes = midi.toArray();
const blob = new Blob([midiBytes], { type: 'audio/midi' });
const url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = `notes_${new Date().getTime()}.mid`;
// 2. Текст
currentTextOutput = "СПИСОК РАСПОЗНАННЫХ НОТ\n----------------------------------------\n";
filteredNotes.forEach((note, index) => {
currentTextOutput += `${index + 1}. Нота: ${midiToNoteName(note.pitchMidi).padEnd(3)} | Время: ${note.startTimeSeconds.toFixed(2)}с | Длит: ${note.durationSeconds.toFixed(2)}с\n`;
});
textResultDiv.textContent = currentTextOutput;
// 3. Рисуем ноты (подгружаем abcjs прямо сейчас)
statusDiv.textContent = 'Отрисовка партитуры...';
if (!window.ABCJS) {
await new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://unpkg.com/abcjs@6.2.2/dist/abcjs-basic-min.js';
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
sheetMusicDiv.innerHTML = "";
if (window.ABCJS) {
window.ABCJS.renderAbc("sheetMusic", abcString, {
scale: 1.5,
add_classes: true,
responsive: "resize"
});
}
resultDiv.style.display = 'block';
statusDiv.textContent = 'Готово!';
statusDiv.className = '';
} catch (error) {
console.error("Детали ошибки:", error);
statusDiv.className = 'error-text';
statusDiv.textContent = 'Ошибка: ' + error.message + '. Проверьте интернет-соединение.';
} finally {
analyzeBtn.disabled = false;
}
});
// --- Скачивание текста ---
downloadTxtBtn.addEventListener('click', () => {
if (!currentTextOutput) return;
const blob = new Blob([currentTextOutput], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `notes_${new Date().getTime()}.txt`;
a.click();
URL.revokeObjectURL(url);
});
});
</script>
</body>
</html> |