Spaces:
Sleeping
Sleeping
File size: 21,646 Bytes
85f00ee 7a85a0b | 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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 | <!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bio-Vibe Web</title>
<link rel="icon" href="data:,">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #1a1a2e;
color: #e94560;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
padding: 20px;
box-sizing: border-box;
}
.container {
background-color: #16213e;
padding: 40px;
border-radius: 15px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
max-width: 620px;
width: 100%;
}
h1 { color: #fff; margin-bottom: 5px; }
.subtitle { color: #a2a2bd; margin-bottom: 20px; }
#bpm-display {
font-size: 80px;
font-weight: bold;
margin: 15px 0;
text-shadow: 0 0 15px #e94560;
transition: color 0.3s ease;
}
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.05); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
/* ---- TABS ---- */
.tab-group {
display: flex;
justify-content: center;
gap: 0;
margin-bottom: 20px;
border-radius: 8px;
overflow: hidden;
border: 1px solid #0f3460;
}
.tab-btn {
flex: 1;
background: #0f3460;
color: #a2a2bd;
border: none;
padding: 10px 16px;
font-size: 14px;
cursor: pointer;
transition: 0.2s;
font-weight: bold;
}
.tab-btn.active { background: #4ecca3; color: #1a1a2e; }
.tab-btn:hover:not(.active) { background: #1a3a6e; color: #fff; }
.tab-panel { display: none; }
.tab-panel.active { display: block; }
/* ---- MANUAL INPUT ---- */
.manual-group {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
margin: 10px 0 16px;
}
#manual-bpm-input {
background: #0f3460;
border: 1px solid #4ecca3;
border-radius: 8px;
color: #fff;
font-size: 28px;
font-weight: bold;
width: 110px;
text-align: center;
padding: 8px;
}
#manual-bpm-input:focus { outline: 2px solid #4ecca3; }
#btn-manual-set {
background: #4ecca3;
color: #1a1a2e;
border: none;
padding: 10px 18px;
font-size: 15px;
border-radius: 8px;
cursor: pointer;
font-weight: bold;
transition: 0.2s;
}
#btn-manual-set:hover { background: #38b499; }
/* ---- BUTTONS ---- */
.button-group {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 12px;
margin-top: 10px;
}
button {
background-color: #0f3460;
color: white;
border: none;
padding: 13px 22px;
font-size: 15px;
border-radius: 8px;
cursor: pointer;
transition: 0.3s;
font-weight: bold;
}
button:hover { background-color: #4ecca3; color: #1a1a2e; }
button:disabled { background-color: #2a2a3e; cursor: not-allowed; color: #555; }
#btn-stop { background-color: #8b0000; }
#btn-stop:hover { background-color: #ff4d4d; color: white; }
#btn-stop:disabled { background-color: #2a2a3e; }
/* ---- STATUS ---- */
#status {
margin-top: 18px;
font-size: 13px;
font-style: italic;
min-height: 20px;
}
.status-ok { color: #4ecca3; }
.status-err { color: #ff4d4d; }
.status-info { color: #a2a2bd; }
/* ---- DEBUG LOG ---- */
.debug-section {
margin-top: 20px;
text-align: left;
}
.debug-toggle {
background: none;
border: none;
color: #555;
font-size: 12px;
cursor: pointer;
padding: 4px 0;
font-style: italic;
}
.debug-toggle:hover { color: #a2a2bd; background: none; }
#debug-log {
display: none;
background: #0a0a1a;
border-radius: 6px;
padding: 10px;
font-size: 11px;
color: #4ecca3;
font-family: monospace;
max-height: 160px;
overflow-y: auto;
margin-top: 6px;
text-align: left;
}
/* ---- NOTICE ---- */
.notice {
background: #0f2040;
border-left: 3px solid #e94560;
border-radius: 0 6px 6px 0;
padding: 10px 14px;
margin-bottom: 14px;
font-size: 13px;
color: #a2a2bd;
text-align: left;
}
.notice strong { color: #e94560; }
</style>
</head>
<body>
<div class="container">
<h1>Bio-Vibe 🎧</h1>
<p class="subtitle">Âm nhạc trị liệu AI theo Nhịp tim</p>
<div id="bpm-display">-- BPM</div>
<!-- TABS -->
<div class="tab-group">
<button class="tab-btn active" onclick="switchTab('ble')">📡 Kết nối BLE</button>
<button class="tab-btn" onclick="switchTab('manual')">✏️ Nhập thủ công</button>
</div>
<!-- TAB: BLE -->
<div id="tab-ble" class="tab-panel active">
<div class="notice">
<strong>Lưu ý Xiaomi / Samsung:</strong> Đồng hồ thông minh dùng giao thức riêng,
không truyền nhịp tim qua BLE chuẩn. Thử kết nối — nếu không ra BPM,
hãy dùng tab <em>Nhập thủ công</em> hoặc một chest-strap HR monitor (Polar, Garmin…).
</div>
<div class="button-group">
<button id="btn-connect">1. Kết nối đồng hồ</button>
</div>
</div>
<!-- TAB: MANUAL -->
<div id="tab-manual" class="tab-panel">
<p style="color:#a2a2bd; font-size:14px; margin-bottom:10px;">
Nhập BPM từ app đồng hồ (Mi Fitness, Samsung Health…) rồi nhấn Set.
</p>
<div class="manual-group">
<input type="number" id="manual-bpm-input" min="30" max="220" value="75" />
<button id="btn-manual-set" onclick="setManualBpm()">Set BPM</button>
</div>
</div>
<!-- PLAYBACK CONTROLS -->
<div class="button-group" style="margin-top:18px;">
<button id="btn-generate">2. Sinh nhạc AI</button>
<button id="btn-stop" disabled>3. Dừng nhạc</button>
</div>
<div id="status" class="status-info">Chưa có BPM...</div>
<!-- DEBUG -->
<div class="debug-section">
<button class="debug-toggle" onclick="toggleDebug()">▶ Xem log BLE debug</button>
<div id="debug-log"></div>
</div>
</div>
<script>
// ===============================
// STATE
// ===============================
let currentBpm = 0;
let bpmHistory = [];
let currentAudio = null;
let debugVisible = false;
let ws = null; // Biến giữ kết nối WebSocket
const bpmDisplay = document.getElementById('bpm-display');
const statusEl = document.getElementById('status');
const btnConnect = document.getElementById('btn-connect');
const btnGenerate = document.getElementById('btn-generate');
const btnStop = document.getElementById('btn-stop');
const debugLog = document.getElementById('debug-log');
// ===============================
// UI HELPERS
// ===============================
function setStatus(msg, type = 'info') {
statusEl.textContent = msg;
statusEl.className = 'status-' + type;
}
function log(msg) {
const line = document.createElement('div');
line.textContent = '[' + new Date().toLocaleTimeString() + '] ' + msg;
debugLog.appendChild(line);
debugLog.scrollTop = debugLog.scrollHeight;
console.log(msg);
}
function toggleDebug() {
debugVisible = !debugVisible;
debugLog.style.display = debugVisible ? 'block' : 'none';
}
function switchTab(name) {
document.querySelectorAll('.tab-btn').forEach((b, i) => {
b.classList.toggle('active', (i === 0 && name === 'ble') || (i === 1 && name === 'manual'));
});
document.getElementById('tab-ble').classList.toggle('active', name === 'ble');
document.getElementById('tab-manual').classList.toggle('active', name === 'manual');
}
// ===============================
// BPM SMOOTHING
// ===============================
function smoothBpm(val) {
bpmHistory.push(val);
if (bpmHistory.length > 5) bpmHistory.shift();
return Math.round(bpmHistory.reduce((a, b) => a + b, 0) / bpmHistory.length);
}
function applyBpm(raw, source) {
if (raw < 30 || raw > 220) return false;
if (currentBpm !== 0 && Math.abs(raw - currentBpm) > 40) return false;
const smoothed = smoothBpm(raw);
currentBpm = smoothed;
bpmDisplay.textContent = currentBpm + ' BPM';
bpmDisplay.style.color = '#e94560';
setStatus('BPM nhận từ: ' + source, 'ok');
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ bpm: currentBpm }));
}
return true;
}
// ===============================
// MANUAL BPM
// ===============================
function setManualBpm() {
const val = parseInt(document.getElementById('manual-bpm-input').value, 10);
if (isNaN(val) || val < 30 || val > 220) {
setStatus('Giá trị BPM không hợp lệ (30–220)', 'err');
return;
}
bpmHistory = [];
applyBpm(val, 'Nhập thủ công');
}
// ===============================
// PARSE CHUẨN BLE Heart Rate (0x2A37)
// ===============================
function parseHeartRateMeasurement(dataView) {
/*
* Byte 0: Flags
* bit 0 = 0 → Heart Rate Value là UINT8 (byte 1)
* bit 0 = 1 → Heart Rate Value là UINT16 (bytes 1-2, little-endian)
*/
const flags = dataView.getUint8(0);
const is16bit = (flags & 0x01) !== 0;
return is16bit
? dataView.getUint16(1, true)
: dataView.getUint8(1);
}
// ===============================
// HANDLE INCOMING CHARACTERISTIC DATA
// ===============================
function handleCharData(event, uuid, serviceUuid) {
const dv = event.target.value;
const raw = [];
for (let i = 0; i < dv.byteLength; i++) raw.push(dv.getUint8(i));
log(`UUID ${uuid.substring(0,8)}… DATA: [${raw.join(', ')}]`);
const HR_MEASUREMENT_UUID = '00002a37-0000-1000-8000-00805f9b34fb';
// 1. Nếu đúng UUID chuẩn Heart Rate Measurement → parse theo spec
if (uuid === HR_MEASUREMENT_UUID) {
if (dv.byteLength >= 2) {
const bpm = parseHeartRateMeasurement(dv);
log(`Standard HR parse → ${bpm} BPM`);
applyBpm(bpm, 'HR chuẩn BLE');
}
return;
}
// 2. Fallback heuristic cho proprietary chars
// Duyệt từng byte, lấy byte đầu tiên nằm trong [40, 180]
for (let i = 0; i < raw.length; i++) {
const v = raw[i];
if (v >= 40 && v <= 180) {
log(`Heuristic byte[${i}] = ${v} BPM`);
applyBpm(v, `Heuristic (${uuid.substring(0,8)}…)`);
break;
}
}
}
// ===============================
// BLE CONNECT — auto scan tất cả services
// ===============================
btnConnect.addEventListener('click', async () => {
if (!navigator.bluetooth) {
setStatus('Trình duyệt không hỗ trợ Web Bluetooth!', 'err');
return;
}
try {
setStatus('Đang mở hộp thoại BLE…', 'info');
log('Bắt đầu scan BLE...');
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: [
// Chuẩn BLE
'heart_rate',
'battery_service',
'device_information',
'generic_access',
// Xiaomi Mi Band 4/5/6/7 — proprietary
'0000fee0-0000-1000-8000-00805f9b34fb',
'0000fee1-0000-1000-8000-00805f9b34fb',
// Xiaomi Mi Band 7 / Amazfit
'0000181d-0000-1000-8000-00805f9b34fb',
// Samsung Galaxy Watch — proprietary health
'0000fd00-0000-1000-8000-00805f9b34fb',
// Generic HR secondary
'0000180d-0000-1000-8000-00805f9b34fb',
]
});
log(`Device: ${device.name || '(no name)'} id=${device.id}`);
setStatus('Đang kết nối GATT…', 'info');
const server = await device.gatt.connect();
const services = await server.getPrimaryServices();
log(`Tìm thấy ${services.length} service(s)`);
let subscribed = 0;
for (const svc of services) {
log(`Service: ${svc.uuid}`);
let chars;
try {
chars = await svc.getCharacteristics();
} catch (e) {
log(` Không đọc được characteristics: ${e.message}`);
continue;
}
for (const char of chars) {
const props = char.properties;
log(` Char: ${char.uuid} [notify=${props.notify} indicate=${props.indicate} read=${props.read}]`);
if (props.notify || props.indicate) {
try {
await char.startNotifications();
char.addEventListener('characteristicvaluechanged',
(ev) => handleCharData(ev, char.uuid, svc.uuid));
log(` ✅ Subscribed: ${char.uuid}`);
subscribed++;
} catch (e) {
log(` ❌ Subscribe failed: ${e.message}`);
}
}
}
}
btnConnect.textContent = '✓ BLE Connected';
btnConnect.disabled = true;
if (subscribed === 0) {
setStatus('Kết nối OK nhưng không có characteristic nào để subscribe. Thử tab Nhập thủ công.', 'err');
} else {
setStatus(`Đã subscribe ${subscribed} characteristic(s), đang chờ BPM…`, 'ok');
}
} catch (err) {
log(`Lỗi: ${err.message}`);
setStatus('Lỗi BLE: ' + err.message, 'err');
}
});
// ===============================
// GENERATE MUSIC
const limiter = new Tone.Limiter(-1);
// 2. Compressor (giữ âm ổn định)
const compressor = new Tone.Compressor({
threshold: -18,
ratio: 3,
attack: 0.01,
release: 0.2
});
// 3. EQ (làm ấm piano)
const eq = new Tone.EQ3({
low: 3, // tăng bass nhẹ
mid: -1, // giảm mid đục
high: 2 // tăng sáng nhẹ
});
// 4. Stereo widen (cho không gian rộng)
const stereo = new Tone.StereoWidener(0.6);
// 5. Reverb (không gian)
const reverb = new Tone.Reverb({
decay: 4,
wet: 0.3
});
// 6. Delay (lofi feel)
const delay = new Tone.FeedbackDelay({
delayTime: "8n",
feedback: 0.25,
wet: 0.15
});
// Connect chain
delay.connect(reverb);
reverb.connect(stereo);
stereo.connect(eq);
eq.connect(compressor);
compressor.connect(limiter);
limiter.toDestination();
const piano = new Tone.Sampler({
urls: {
A1: "A1.mp3",
C2: "C2.mp3",
"D#2": "Ds2.mp3",
"F#2": "Fs2.mp3",
A2: "A2.mp3",
C3: "C3.mp3",
"D#3": "Ds3.mp3",
"F#3": "Fs3.mp3",
A3: "A3.mp3",
C4: "C4.mp3",
"D#4": "Ds4.mp3",
"F#4": "Fs4.mp3",
A4: "A4.mp3",
C5: "C5.mp3"
},
baseUrl: "https://raw.githubusercontent.com/Tonejs/audio/master/salamander/",
release: 1
}).connect(delay);
// 🌊 PAD (chord)
const pad = new Tone.PolySynth(Tone.Synth, {
volume: -12,
oscillator: { type: "sine" },
envelope: {
attack: 1,
decay: 0.5,
sustain: 0.8,
release: 3
}
}).connect(reverb);
// 🥁 KICK
const kick = new Tone.MembraneSynth({
volume: -8,
pitchDecay: 0.05,
octaves: 6,
envelope: {
attack: 0.001,
decay: 0.3,
sustain: 0
}
}).connect(compressor);
// 🥁 SNARE
const snare = new Tone.NoiseSynth({
volume: -9,
noise: { type: "white" },
envelope: {
attack: 0.001,
decay: 0.15,
sustain: 0
}
}).connect(compressor);
// Gọi Tone.start() sẵn khi load trang nếu được
log("🎹 Đã khởi tạo Lo-fi Synthesizer (Có Limiter chống rè).");
setStatus("Sẵn sàng sinh nhạc AI", "ok");
// ===============================
// GENERATE MUSIC (CẬP NHẬT WEBSOCKET)
// ===============================
btnGenerate.addEventListener('click', async () => {
if (currentBpm === 0) {
alert('Chưa có BPM! Kết nối đồng hồ hoặc nhập thủ công.');
return;
}
// Bắt buộc trình duyệt cho phép phát âm thanh
await Tone.start();
await Tone.loaded();
console.log("✅ Piano samples loaded");
if (ws) ws.close(); // Đóng kết nối cũ nếu có
setStatus(`Đang kết nối não AI với ${currentBpm} BPM…`, 'info');
btnGenerate.textContent = 'AI đang truyền nốt…';
btnGenerate.disabled = true;
btnStop.disabled = false;
bpmDisplay.style.animation = 'pulse 1s infinite';
// Mở kết nối WebSocket tới Server
// ĐOẠN CODE MỚI ĐÃ FIX LỖI:
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws/vibe`;
ws = new WebSocket(wsUrl);
ws.onopen = () => {
setStatus('🎵 Đang phát nhạc Real-time vô tận…', 'ok');
// Gửi BPM lên server để AI lấy tempo
ws.send(JSON.stringify({ bpm: currentBpm }));
};
let startTime = Tone.now() + 0.1; // Thời gian bắt đầu chơi nhạc, cách hiện tại 100ms để đảm bảo đồng bộ
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
data.notes.forEach(n => {
const note = Tone.Frequency(n.note, "midi").toNote();
const t = startTime + n.time; // 🔥 timeline chuẩn
if (n.type === "melody") {
piano.triggerAttackRelease(note, n.duration, t);
}
else if (n.type === "chord") {
pad.triggerAttackRelease(note, n.duration, t);
}
else if (n.type === "drum") {
if (n.note === 36) kick.triggerAttackRelease("C1", "8n", t);
if (n.note === 38) snare.triggerAttackRelease("16n", t);
}
});
startTime += data.step * 16; // advance timeline
};
ws.onerror = (err) => {
log('WebSocket Error: ' + err);
setStatus('Lỗi kết nối tới AI!', 'err');
};
ws.onclose = () => {
btnGenerate.textContent = '2. Sinh nhạc AI';
btnGenerate.disabled = false;
btnStop.disabled = true;
bpmDisplay.style.animation = 'none';
};
});
// ===============================
// STOP MUSIC (CẬP NHẬT WEBSOCKET)
// ===============================
btnStop.addEventListener('click', () => {
if (ws) {
ws.close(); // Cắt kết nối, Server sẽ tự động dừng suy luận
ws = null;
}
piano.releaseAll(); // Ngắt ngay lập tức các âm vang còn sót lại
setStatus('Đã dừng nhạc.', 'info');
});
</script>
</body>
</html> |