Spaces:
Running
Running
Download index.html from Miberd/music_notes: direct link, hf CLI and curl.
- Browser
- Download file 24.7 kB
-
https://huggingface.co/spaces/Miberd/music_notes/resolve/main/index.html
- Command line
-
hf download hf://spaces/Miberd/music_notes/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Miberd/music_notes/resolve/main/index.html
24.7 kB
| <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 ; 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> |