Spaces:
Running
Running
Download index.html from JetTHSu/AIGuitarMaster: direct link, hf CLI and curl.
- Browser
- Download file 22.3 kB
-
https://huggingface.co/spaces/JetTHSu/AIGuitarMaster/resolve/main/index.html
- Command line
-
hf download hf://spaces/JetTHSu/AIGuitarMaster/index.html
-
curl -L -o index.html https://huggingface.co/spaces/JetTHSu/AIGuitarMaster/resolve/main/index.html
22.3 kB
| <html lang="zh-TW"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>GuitarMaster AI - 吉他和弦與音符即時辨識</title> | |
| <!-- 載入 Tailwind CSS 打造現代感響應式介面 --> | |
| <script src="https://cdn.tailwindcss.com"></script> | |
| <!-- 載入 Google Fonts Inter 字體 --> | |
| <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"> | |
| <style> | |
| body { font-family: 'Inter', sans-serif; } | |
| .pulse-ring { | |
| animation: pulse-animation 1.5s infinite; | |
| } | |
| @keyframes pulse-animation { | |
| 0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); } | |
| 70% { box-shadow: 0 0 0 15px rgba(239, 68, 68, 0); } | |
| 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } | |
| } | |
| </style> | |
| </head> | |
| <body class="bg-slate-950 text-slate-100 min-h-screen flex flex-col items-center p-4 sm:p-8"> | |
| <!-- 頂部標題區塊 --> | |
| <header class="max-w-4xl w-full text-center mb-8"> | |
| <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-amber-500/10 border border-amber-500/30 text-amber-400 text-xs font-medium mb-3"> | |
| <span>⚡ Powered by Spotify Basic Pitch & TensorFlow.js</span> | |
| </div> | |
| <h1 class="text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-r from-amber-400 via-orange-400 to-rose-400 bg-clip-text text-transparent"> | |
| 🎸 GuitarMaster AI | |
| </h1> | |
| <p class="text-slate-400 mt-2 text-sm sm:text-base"> | |
| 純瀏覽器端 AI 吉他和弦與音符辨識系統(Hugging Face Static 免費雲端版) | |
| </p> | |
| </header> | |
| <!-- 模型載入狀態提示列 --> | |
| <div id="modelStatusBanner" class="max-w-4xl w-full mb-6 p-4 rounded-2xl bg-slate-900 border border-slate-800 flex items-center justify-between"> | |
| <div class="flex items-center gap-3"> | |
| <div id="statusDot" class="w-3 h-3 rounded-full bg-amber-400 animate-ping"></div> | |
| <span id="statusText" class="text-sm font-medium text-slate-300">正在從雲端載入 Spotify Basic Pitch AI 模型,請稍候...</span> | |
| </div> | |
| <span id="statusBadge" class="text-xs px-2.5 py-1 rounded-lg bg-amber-500/20 text-amber-300 font-semibold">載入中</span> | |
| </div> | |
| <!-- 主要操作與結果雙欄區 --> | |
| <main class="max-w-4xl w-full grid grid-cols-1 md:grid-cols-2 gap-6"> | |
| <!-- 左側:錄音與上傳控制區 --> | |
| <section class="bg-slate-900/80 border border-slate-800 rounded-3xl p-6 flex flex-col justify-between shadow-xl"> | |
| <div> | |
| <h2 class="text-lg font-semibold text-white mb-1">1. 輸入吉他演奏音訊</h2> | |
| <p class="text-xs text-slate-400 mb-6">點擊麥克風直接彈奏(建議彈奏 2~4 秒),或上傳現有音檔。</p> | |
| <!-- 麥克風錄音按鈕區 --> | |
| <div class="flex flex-col items-center justify-center p-6 rounded-2xl bg-slate-950/60 border border-slate-800/80 mb-5"> | |
| <button id="recordBtn" disabled class="w-20 h-20 rounded-full bg-rose-600 hover:bg-rose-500 disabled:bg-slate-700 disabled:cursor-not-allowed text-white flex items-center justify-center transition-all shadow-lg mb-3"> | |
| <svg id="micIcon" class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"> | |
| <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"></path> | |
| </svg> | |
| </button> | |
| <span id="recordLabel" class="text-sm font-medium text-slate-300">等待模型載入完成...</span> | |
| <span id="timerLabel" class="text-xs text-rose-400 font-mono mt-1 hidden">00:00</span> | |
| </div> | |
| <!-- 分隔線 --> | |
| <div class="relative flex py-2 items-center mb-5"> | |
| <div class="flex-grow border-t border-slate-800"></div> | |
| <span class="flex-shrink mx-4 text-xs text-slate-500">或上傳音訊檔案</span> | |
| <div class="flex-grow border-t border-slate-800"></div> | |
| </div> | |
| <!-- 檔案上傳區 --> | |
| <label class="flex flex-col items-center justify-center w-full p-4 border-2 border-dashed border-slate-700 hover:border-amber-500/50 rounded-2xl cursor-pointer bg-slate-950/40 transition-colors"> | |
| <span class="text-sm text-slate-300 font-medium">📁 選擇 WAV / MP3 / M4A 音檔</span> | |
| <span class="text-xs text-slate-500 mt-1">支援手機錄音檔直接分析</span> | |
| <input id="audioFileInput" type="file" accept="audio/*" disabled class="hidden" /> | |
| </label> | |
| </div> | |
| <!-- 音訊播放器預覽 --> | |
| <div id="audioPreviewBox" class="mt-6 hidden"> | |
| <p class="text-xs text-slate-400 mb-2">音訊預覽:</p> | |
| <audio id="audioPlayer" controls class="w-full h-10 rounded-lg"></audio> | |
| </div> | |
| </section> | |
| <!-- 右側:AI 辨識結果區 --> | |
| <section class="bg-slate-900/80 border border-slate-800 rounded-3xl p-6 flex flex-col shadow-xl"> | |
| <h2 class="text-lg font-semibold text-white mb-1">2. AI 辨識與樂理分析</h2> | |
| <p class="text-xs text-slate-400 mb-6">即時拆解多音音高並自動推算吉他和弦組成。</p> | |
| <!-- 主要和弦結果卡片 --> | |
| <div class="p-6 rounded-2xl bg-gradient-to-br from-slate-800/80 to-slate-900 border border-slate-700/60 text-center mb-5"> | |
| <span class="text-xs uppercase tracking-wider text-amber-400 font-semibold">偵測到的和弦 (Detected Chord)</span> | |
| <div id="chordResult" class="text-3xl sm:text-4xl font-bold text-white my-3"> | |
| -- | |
| </div> | |
| <p id="chordSubtext" class="text-xs text-slate-400">請開始錄音或上傳吉他音檔以進行分析</p> | |
| </div> | |
| <!-- 偵測到的音符標籤雲 --> | |
| <div class="mb-4"> | |
| <h3 class="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">組成音符 (Detected Notes)</h3> | |
| <div id="notesBadges" class="flex flex-wrap gap-2 min-h-[36px] p-3 rounded-xl bg-slate-950/60 border border-slate-800/80"> | |
| <span class="text-xs text-slate-500">尚未偵測到音符</span> | |
| </div> | |
| </div> | |
| <!-- 詳細時間軸事件列表 --> | |
| <div class="flex-grow flex flex-col"> | |
| <h3 class="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">音符時間軸明細</h3> | |
| <div id="noteTimeline" class="flex-grow max-h-44 overflow-y-auto p-3 rounded-xl bg-slate-950/60 border border-slate-800/80 text-xs font-mono text-slate-300 space-y-1.5"> | |
| <div class="text-slate-500">等待音訊輸入...</div> | |
| </div> | |
| </div> | |
| </section> | |
| </main> | |
| <!-- 自訂訊息提示框 (取代 alert) --> | |
| <div id="toastBox" class="fixed bottom-5 right-5 max-w-sm bg-slate-800 border border-slate-700 text-white px-4 py-3 rounded-2xl shadow-2xl text-sm hidden transition-opacity"></div> | |
| <script type="module"> | |
| // 使用官方支援的 ES Module CDN 載入 TensorFlow.js 與 Spotify Basic Pitch | |
| import * as tf from 'https://esm.sh/@tensorflow/tfjs@4.17.0'; | |
| import { BasicPitch, outputToNotesPoly, noteFramesToTime } from 'https://esm.sh/@spotify/basic-pitch@1.0.1'; | |
| // ========================================== | |
| // 1. 全域變數與 DOM 元素初始化 | |
| // ========================================== | |
| let basicPitchModel = null; | |
| let mediaRecorder = null; | |
| let audioChunks = []; | |
| let isRecording = false; | |
| let timerInterval = null; | |
| let recordSeconds = 0; | |
| // 使用穩定支援 CORS 的 jsDelivr CDN 載入 Spotify 預訓練模型權重 | |
| const MODEL_URL = 'https://cdn.jsdelivr.net/npm/@spotify/basic-pitch@1.0.1/model/model.json'; | |
| const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']; | |
| // 常見吉他和弦指紋庫 (相對於根音的半音距離) | |
| const CHORD_PATTERNS = [ | |
| { name: 'Major (大三和弦)', suffix: '', intervals: [0, 4, 7] }, | |
| { name: 'Minor (小三和弦)', suffix: 'm', intervals: [0, 3, 7] }, | |
| { name: 'Dominant 7th (屬七和弦)', suffix: '7', intervals: [0, 4, 7, 10] }, | |
| { name: 'Major 7th (大七和弦)', suffix: 'maj7', intervals: [0, 4, 7, 11] }, | |
| { name: 'Minor 7th (小七和弦)', suffix: 'm7', intervals: [0, 3, 7, 10] }, | |
| { name: 'Sus4 (掛留四和弦)', suffix: 'sus4', intervals: [0, 5, 7] }, | |
| { name: 'Sus2 (掛留二和弦)', suffix: 'sus2', intervals: [0, 2, 7] }, | |
| { name: 'Power Chord (強力五和弦)', suffix: '5', intervals: [0, 7] } | |
| ]; | |
| function showToast(msg) { | |
| const toast = document.getElementById('toastBox'); | |
| toast.textContent = msg; | |
| toast.classList.remove('hidden'); | |
| setTimeout(() => toast.classList.add('hidden'), 4000); | |
| } | |
| // ========================================== | |
| // 2. 載入 Spotify Basic Pitch 網頁版 AI 模型 | |
| // ========================================== | |
| async function initModel() { | |
| try { | |
| await tf.ready(); | |
| // 使用 @spotify/basic-pitch 載入預訓練權重 | |
| basicPitchModel = new BasicPitch(MODEL_URL); | |
| // 等待模型權重完全下載並初始化 | |
| await basicPitchModel.model; | |
| document.getElementById('statusDot').className = 'w-3 h-3 rounded-full bg-emerald-400'; | |
| document.getElementById('statusText').textContent = 'Spotify Basic Pitch AI 模型已就緒!可以開始彈奏吉他。'; | |
| const badge = document.getElementById('statusBadge'); | |
| badge.textContent = '已就緒'; | |
| badge.className = 'text-xs px-2.5 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 font-semibold'; | |
| document.getElementById('recordBtn').disabled = false; | |
| document.getElementById('audioFileInput').disabled = false; | |
| document.getElementById('recordLabel').textContent = '點擊紅色按鈕開始錄音'; | |
| } catch (error) { | |
| console.error('模型載入失敗:', error); | |
| document.getElementById('statusDot').className = 'w-3 h-3 rounded-full bg-rose-500'; | |
| document.getElementById('statusText').textContent = `模型載入失敗 (${error.message}),請重新整理頁面。`; | |
| const badge = document.getElementById('statusBadge'); | |
| badge.textContent = '載入失敗'; | |
| badge.className = 'text-xs px-2.5 py-1 rounded-lg bg-rose-500/20 text-rose-300 font-semibold'; | |
| } | |
| } | |
| // ========================================== | |
| // 3. 麥克風錄音與檔案上傳處理 | |
| // ========================================== | |
| document.getElementById('recordBtn').addEventListener('click', async () => { | |
| if (!isRecording) { | |
| try { | |
| const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
| mediaRecorder = new MediaRecorder(stream); | |
| audioChunks = []; | |
| mediaRecorder.ondataavailable = e => { | |
| if (e.data.size > 0) audioChunks.push(e.data); | |
| }; | |
| mediaRecorder.onstop = async () => { | |
| const audioBlob = new Blob(audioChunks, { type: 'audio/webm' }); | |
| const audioUrl = URL.createObjectURL(audioBlob); | |
| const player = document.getElementById('audioPlayer'); | |
| player.src = audioUrl; | |
| document.getElementById('audioPreviewBox').classList.remove('hidden'); | |
| // 停止所有麥克風音軌釋放資源 | |
| stream.getTracks().forEach(track => track.stop()); | |
| await processAudioBlob(audioBlob); | |
| }; | |
| mediaRecorder.start(); | |
| isRecording = true; | |
| recordSeconds = 0; | |
| const btn = document.getElementById('recordBtn'); | |
| btn.classList.add('pulse-ring', 'bg-rose-500'); | |
| document.getElementById('recordLabel').textContent = '正在聆聽吉他聲... 再次點擊結束'; | |
| const timer = document.getElementById('timerLabel'); | |
| timer.classList.remove('hidden'); | |
| timer.textContent = '00:00'; | |
| timerInterval = setInterval(() => { | |
| recordSeconds++; | |
| const mins = String(Math.floor(recordSeconds / 60)).padStart(2, '0'); | |
| const secs = String(recordSeconds % 60).padStart(2, '0'); | |
| timer.textContent = `${mins}:${secs}`; | |
| }, 1000); | |
| } catch (err) { | |
| showToast('無法存取麥克風,請確認瀏覽器已允許麥克風權限!'); | |
| } | |
| } else { | |
| mediaRecorder.stop(); | |
| isRecording = false; | |
| clearInterval(timerInterval); | |
| document.getElementById('recordBtn').classList.remove('pulse-ring'); | |
| document.getElementById('recordLabel').textContent = 'AI 正在分析音訊,請稍候...'; | |
| document.getElementById('timerLabel').classList.add('hidden'); | |
| } | |
| }); | |
| document.getElementById('audioFileInput').addEventListener('change', async (e) => { | |
| const file = e.target.files[0]; | |
| if (!file) return; | |
| const audioUrl = URL.createObjectURL(file); | |
| const player = document.getElementById('audioPlayer'); | |
| player.src = audioUrl; | |
| document.getElementById('audioPreviewBox').classList.remove('hidden'); | |
| await processAudioBlob(file); | |
| }); | |
| // ========================================== | |
| // 4. 音訊重採樣 (22050Hz 單聲道) 與 AI 推論 | |
| // ========================================== | |
| async function processAudioBlob(blob) { | |
| document.getElementById('chordResult').textContent = '分析中...'; | |
| document.getElementById('chordSubtext').textContent = 'Spotify Basic Pitch 模型正在提取音高特徵'; | |
| try { | |
| const arrayBuffer = await blob.arrayBuffer(); | |
| const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); | |
| const decodedBuffer = await audioCtx.decodeAudioData(arrayBuffer); | |
| // Basic Pitch 模型標準輸入為 22050Hz 單聲道音訊 | |
| const targetSampleRate = 22050; | |
| const offlineCtx = new OfflineAudioContext(1, Math.ceil(decodedBuffer.duration * targetSampleRate), targetSampleRate); | |
| const source = offlineCtx.createBufferSource(); | |
| source.buffer = decodedBuffer; | |
| source.connect(offlineCtx.destination); | |
| source.start(0); | |
| const resampledBuffer = await offlineCtx.startRendering(); | |
| const frames = []; | |
| const onsets = []; | |
| const contours = []; | |
| // 執行模型推論 | |
| await basicPitchModel.evaluateModel( | |
| resampledBuffer, | |
| (f, o, c) => { | |
| frames.push(...f); | |
| onsets.push(...o); | |
| contours.push(...c); | |
| }, | |
| () => {} | |
| ); | |
| // 將模型輸出轉換為 MIDI 音符事件 (onsetThreshold=0.5, frameThreshold=0.3, minNoteLength=11 frames) | |
| const rawNotes = outputToNotesPoly(frames, onsets, 0.5, 0.3, 11); | |
| const noteEvents = noteFramesToTime(rawNotes); | |
| renderResults(noteEvents); | |
| document.getElementById('recordLabel').textContent = '點擊紅色按鈕開始錄音'; | |
| } catch (err) { | |
| console.error('音訊分析失敗:', err); | |
| showToast('音訊解碼或分析失敗,請嘗試重新錄製一段 2~5 秒的音訊。'); | |
| document.getElementById('chordResult').textContent = '分析錯誤'; | |
| document.getElementById('recordLabel').textContent = '點擊紅色按鈕開始錄音'; | |
| } | |
| } | |
| // ========================================== | |
| // 5. 樂理和弦推算演算法 & 畫面渲染 | |
| // ========================================== | |
| function midiToNoteName(midi) { | |
| const note = NOTE_NAMES[midi % 12]; | |
| const octave = Math.floor(midi / 12) - 1; | |
| return `${note}${octave}`; | |
| } | |
| function detectChordFromMidi(midiNumbers) { | |
| if (midiNumbers.length === 0) return { chord: '無音符', desc: '未偵測到有效音高' }; | |
| if (midiNumbers.length === 1) { | |
| const singleNote = NOTE_NAMES[midiNumbers[0] % 12]; | |
| return { chord: `${singleNote} (單音)`, desc: '僅偵測到單一音符,請嘗試同時刷多個弦' }; | |
| } | |
| // 取得不重複的音級 (0=C, 1=C#, ..., 11=B),並找出最低音作為可能根音參考 | |
| const sortedMidi = [...midiNumbers].sort((a, b) => a - b); | |
| const lowestPitchClass = sortedMidi[0] % 12; | |
| const pitchClasses = [...new Set(sortedMidi.map(m => m % 12))]; | |
| let bestMatch = null; | |
| let bestScore = -1; | |
| // 遍歷所有偵測到的音級作為候選根音 | |
| for (const root of pitchClasses) { | |
| const intervals = pitchClasses.map(pc => (pc - root + 12) % 12); | |
| for (const pattern of CHORD_PATTERNS) { | |
| // 計算符合該和弦指紋的音符數量 | |
| const matched = pattern.intervals.filter(iv => intervals.includes(iv)); | |
| if (matched.length === pattern.intervals.length) { | |
| // 加分權重:符合音符越多越好,且如果候選根音剛好是最低音(Bass音)則額外加分 | |
| let score = matched.length * 10 - (pitchClasses.length - matched.length) * 2; | |
| if (root === lowestPitchClass) score += 5; | |
| if (score > bestScore) { | |
| bestScore = score; | |
| bestMatch = { | |
| chord: `${NOTE_NAMES[root]}${pattern.suffix}`, | |
| desc: `識別為 ${NOTE_NAMES[root]} ${pattern.name}` | |
| }; | |
| } | |
| } | |
| } | |
| } | |
| if (bestMatch) return bestMatch; | |
| const noteList = pitchClasses.map(pc => NOTE_NAMES[pc]).join(' - '); | |
| return { | |
| chord: '複合和音 / 轉位', | |
| desc: `偵測到組成音:${noteList}` | |
| }; | |
| } | |
| function renderResults(noteEvents) { | |
| const chordEl = document.getElementById('chordResult'); | |
| const subtextEl = document.getElementById('chordSubtext'); | |
| const badgesEl = document.getElementById('notesBadges'); | |
| const timelineEl = document.getElementById('noteTimeline'); | |
| if (!noteEvents || noteEvents.length === 0) { | |
| chordEl.textContent = '未偵測到音符'; | |
| subtextEl.textContent = '請靠近麥克風並彈大聲一點再試一次!'; | |
| badgesEl.innerHTML = '<span class="text-xs text-slate-500">無音符資料</span>'; | |
| timelineEl.innerHTML = '<div class="text-slate-500">無偵測事件</div>'; | |
| return; | |
| } | |
| // 依時間排序 | |
| const sortedEvents = [...noteEvents].sort((a, b) => a.startTimeSeconds - b.startTimeSeconds); | |
| const midiList = sortedEvents.map(n => n.pitchMidi); | |
| // 1. 更新和弦顯示 | |
| const chordInfo = detectChordFromMidi(midiList); | |
| chordEl.textContent = chordInfo.chord; | |
| subtextEl.textContent = `${chordInfo.desc}(共偵測到 ${sortedEvents.length} 個音符)`; | |
| // 2. 更新獨立音符標籤 | |
| const uniqueNotes = [...new Set(midiList.map(m => midiToNoteName(m)))]; | |
| badgesEl.innerHTML = uniqueNotes.map(note => ` | |
| <span class="px-3 py-1 rounded-lg bg-amber-500/20 border border-amber-500/40 text-amber-300 text-xs font-bold"> | |
| ${note} | |
| </span> | |
| `).join(''); | |
| // 3. 更新時間軸明細 | |
| timelineEl.innerHTML = sortedEvents.map(n => { | |
| const start = n.startTimeSeconds.toFixed(2); | |
| const end = (n.startTimeSeconds + n.durationSeconds).toFixed(2); | |
| const noteName = midiToNoteName(n.pitchMidi); | |
| const amp = Math.round(n.amplitude * 100); | |
| return ` | |
| <div class="flex justify-between items-center py-1 px-2 rounded bg-slate-900/80"> | |
| <span>⏱️ ${start}s ~ ${end}s</span> | |
| <span class="text-amber-400 font-bold">${noteName}</span> | |
| <span class="text-slate-400">力度 ${amp}%</span> | |
| </div> | |
| `; | |
| }).join(''); | |
| } | |
| // 網頁載入後立即初始化模型 | |
| initModel(); | |
| </script> | |
| </body> | |
| </html> |