同题横评:做一个网页版的电子琴,声音逼真,外观也仿真立体
结论速览
> 本报告由「AI 大众点评 · 同题横评工作台」自动生成,同一任务并发调用多家大模型后对比输出。
本次横评产品(4)
横评任务
做一个网页版的电子琴,声音逼真,外观也仿真立体
冠军DeepSeek7.8综合分 / 10 | 亚军Kimi6.7综合分 / 10 | 季军智谱 GLM3.9综合分 / 10 | 第 4 名百度文心1.4综合分 / 10 | 调用失败豆包—综合分 / 10 | 调用失败通义千问—综合分 / 10 | |
|---|---|---|---|---|---|---|
| 综合分 | 7.8 | 6.7 | 3.9 | 1.4 | 调用失败 | 调用失败 |
| 质量分 | 8.5 | 8.9 | 1.7 | 1.7 | — | — |
| 性能分 | 6.1 | 1.5 | 9.0 | 0.7 | — | — |
| 正确性/可运行性 | 9.0 | 9.0 | 1.0 | 1.0 | — | — |
| 逻辑性 | 8.0 | 8.5 | 1.5 | 1.0 | — | — |
| 完整性 | 8.8 | 10.0 | 1.3 | 1.3 | — | — |
| 稳定性 | 8.0 | 8.5 | 1.0 | 1.0 | — | — |
| 风格 | 8.5 | 8.5 | 3.0 | 5.0 | — | — |
| 效率 | 7.0 | 7.0 | 7.0 | 6.0 | — | — |
| 响应耗时 | 32.3s | 194.2s | 38.4s | 221.2s | — | — |
| Token(入/出) | 18 / 8091 | 20 / 7559 | 19 / 905 | 15 / 9994 | — | — |
| 调用费用(估算) | ¥0.02 | ¥0.12 | 免费 | ¥0.18 | — | — |
| 单位产出成本 | ¥0.0026 / 分 | ¥0.0179 / 分 | 翻车·不计 | 截断·不计 | — | — |
高亮为该指标最优值。综合分 = 质量分 × 70% + 性能分 × 30%;性能分 = 速度 45% + Token 效率 40% + 费用 15%(费用项最高 8 分);质量分为六维人工打分加权(正确性/可运行性 30% + 逻辑性 25% + 完整性 20% + 稳定性 10% + 风格 10% + 效率 5%)。输出被截断或可运行性 ≤ 2 时,综合分封顶 4.0。
调用费用为按各模型官方刊例价 × 真实 token 用量折算的估算值,仅代表平台 API 成本;用户使用本站横评无需付费,命中缓存的横评不产生新费用。单位产出成本 = 调用费用 ÷ 综合分,即「每得 1 分综合分的成本」,越低越划算;输出截断或可运行性 ≤ 2 的样本标注「不计」,不参与最优值比较,以免劣质结果显得便宜。
输出对比
产物可直接在线试玩(等比缩放),下方仅展示实现要点,完整源码默认折叠。
实现要点
以下是您需要的网页版电子琴HTML代码。它拥有逼真的立体外观和声音,并支持鼠标与键盘弹奏。
弹奏体验与核心机制
您可以通过鼠标点击或电脑键盘来弹奏钢琴,每个琴键都对应着真实的音高。为了让声音更逼真,代码使用了多层波形合成技术。
- 弹奏方式:直接用鼠标点击琴键即可发声。同时,您也可以使用电脑键盘,低八度对应字母区(A到J等),高八度对应K到N等键位,具体映射可以参考代码中的`preciseKeyMap`。
- 声音合成:每个音符的声音都由三个不同频率和波形的振荡器混合而成(正弦波、三角波和低八度正弦波),并配合快速的起音和自然的衰减包络,模拟了钢琴的听感。
- 视觉反馈:琴键被按下时会有下沉和颜色变化的效果,同时整体琴架带有微妙的3D透视和光影,增强了立体感和操作的真实感。
查看完整源码
以下是您需要的网页版电子琴HTML代码。它拥有逼真的立体外观和声音,并支持鼠标与键盘弹奏。
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>立体声电子琴 · 仿真钢琴</title>
<style>
* {
box-sizing: border-box;
user-select: none;
}
body {
margin: 0;
min-height: 100vh;
background: radial-gradient(circle at 30% 10%, #3e3e4e, #1e1e24);
display: flex;
justify-content: center;
align-items: center;
font-family: 'Segoe UI', 'Arial', sans-serif;
padding: 16px;
}
/* 琴架与立体阴影 */
.piano-stand {
position: relative;
padding: 20px 18px 30px;
background: linear-gradient(145deg, #2c2c2e, #1a1a1c);
border-radius: 30px 30px 18px 18px;
box-shadow:
0 30px 40px rgba(0, 0, 0, 0.8),
0 8px 20px rgba(0, 0, 0, 0.6),
inset 0 1px 4px rgba(255, 255, 255, 0.1),
inset 0 -4px 8px rgba(0, 0, 0, 0.8);
transform: perspective(1200px) rotateX(4deg) rotateY(-2deg);
transition: transform 0.2s ease;
}
/* 增加一点微动效,更立体 */
.piano-stand:hover {
transform: perspective(1200px) rotateX(5deg) rotateY(-2.5deg);
}
/* 键盘外壳,木质/金属质感 */
.keyboard-shell {
background: linear-gradient(180deg, #3b3b3f, #242428);
border-radius: 18px 18px 14px 14px;
padding: 10px 10px 18px;
box-shadow:
inset 0 2px 6px rgba(255, 255, 255, 0.1),
inset 0 -6px 8px rgba(0, 0, 0, 0.5),
0 12px 18px rgba(0, 0, 0, 0.6);
border-bottom: 6px solid #111114;
}
/* 琴键区域 */
.keys-container {
display: flex;
justify-content: center;
align-items: flex-start;
position: relative;
height: 220px;
padding: 0 6px;
background: #1b1b1f;
border-radius: 10px;
box-shadow: inset 0 5px 15px rgba(0, 0, 0, 0.9), 0 5px 0 #0b0b0e;
overflow: hidden;
}
/* 白键独立容器,为了立体排列 */
.white-keys {
display: flex;
gap: 2px;
height: 100%;
padding: 6px 0 0;
}
.white-key {
width: 58px;
height: 210px;
background: linear-gradient(180deg, #fcfcfc, #e2e2e2, #b5b5b5);
border-radius: 0 0 10px 10px;
box-shadow:
0 6px 0 #7f7f7f,
0 12px 16px rgba(0, 0, 0, 0.5),
inset 0 1px 0 white,
inset 0 -6px 8px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition: all 0.04s linear;
position: relative;
border: 1px solid #aaa;
border-top: none;
transform-origin: top center;
}
.white-key:active,
.white-key.active {
transform: translateY(5px);
height: 205px;
box-shadow:
0 2px 0 #5f5f5f,
0 8px 12px rgba(0, 0, 0, 0.5),
inset 0 1px 0 white,
inset 0 -4px 6px rgba(0, 0, 0, 0.3);
background: linear-gradient(180deg, #e0e0e0, #cfcfcf, #a0a0a0);
}
/* 黑键定位区域 */
.black-keys-container {
position: absolute;
top: 6px;
left: 0;
width: 100%;
height: 140px;
pointer-events: none;
display: flex;
justify-content: flex-start;
padding-left: 6px;
}
/* 因为黑键对齐白键,使用flex和间距模拟 */
.black-keys {
display: flex;
gap: 2px;
height: 100%;
align-items: flex-start;
padding-left: 30px; /* 第一个黑键位置 (白键宽58+gap2=60, 黑键起始偏移) */
pointer-events: none;
}
.black-key {
width: 36px;
height: 130px;
background: linear-gradient(180deg, #2a2a2c, #111113, #060608);
border-radius: 0 0 8px 8px;
box-shadow:
0 5px 0 #000,
0 10px 12px rgba(0, 0, 0, 0.8),
inset 0 1px 0 #555,
inset 0 -4px 6px #000;
cursor: pointer;
pointer-events: auto;
transition: all 0.04s linear;
border: 1px solid #222;
border-top: none;
transform-origin: top center;
z-index: 10;
margin-right: 24px; /* 适配间距:每个黑键后间隔白键宽+gap (58+2=60) 减去黑键宽36 = 24 */
}
/* 调整最后一个黑键的间距 */
.black-key:last-child {
margin-right: 0;
}
/* 黑键按下状态 */
.black-key:active,
.black-key.active {
transform: translateY(4px);
height: 126px;
background: linear-gradient(180deg, #1a1a1c, #0a0a0c, #000);
box-shadow:
0 1px 0 #000,
0 6px 8px rgba(0, 0, 0, 0.8),
inset 0 1px 0 #444,
inset 0 -2px 4px #000;
}
/* 琴键上的文字(音名) */
.key-label {
position: absolute;
bottom: 8px;
left: 0;
width: 100%;
text-align: center;
font-size: 11px;
font-weight: 600;
color: #3a3a3a;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.4);
pointer-events: none;
letter-spacing: 0.5px;
}
.black-key .key-label {
color: #ccc;
text-shadow: 0 0 2px black;
bottom: 6px;
font-size: 9px;
}
/* 顶部装饰条 */
.brand-bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 14px 2px;
color: #b0b0b8;
text-shadow: 0 1px 2px black;
font-size: 12px;
letter-spacing: 3px;
font-weight: 500;
border-bottom: 1px solid #444;
margin-bottom: 8px;
}
.brand {
color: #ddd;
font-weight: 700;
font-size: 15px;
letter-spacing: 2px;
background: linear-gradient(180deg, #eee, #888);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
text-shadow: 0 1px 2px black;
}
.led {
width: 8px;
height: 8px;
border-radius: 50%;
background: #2ecc71;
box-shadow: 0 0 8px #2ecc71, 0 0 4px #2ecc71;
animation: pulse 1.8s infinite;
}
@keyframes pulse {
0% { opacity: 0.7; box-shadow: 0 0 4px #2ecc71; }
50% { opacity: 1; box-shadow: 0 0 12px #2ecc71; }
100% { opacity: 0.7; box-shadow: 0 0 4px #2ecc71; }
}
/* 底部铭牌 */
.footer-plate {
display: flex;
justify-content: center;
margin-top: 12px;
font-size: 11px;
color: #6a6a72;
text-transform: uppercase;
letter-spacing: 4px;
text-shadow: 0 1px 0 #0a0a0a;
}
/* 移动端适配:缩放 */
@media (max-width: 700px) {
.piano-stand {
transform: perspective(1200px) rotateX(2deg) scale(0.85);
padding: 12px 8px 18px;
}
.white-key {
width: 44px;
height: 160px;
}
.white-key:active, .white-key.active {
height: 156px;
}
.keys-container {
height: 170px;
}
.black-key {
width: 28px;
height: 100px;
margin-right: 18px;
}
.black-key:active, .black-key.active {
height: 97px;
}
.black-keys {
padding-left: 24px;
}
.black-keys-container {
height: 110px;
}
}
</style>
</head>
<body>
<div class="piano-stand">
<div class="keyboard-shell">
<div class="brand-bar">
<span class="brand">🎹 STEREO PIANO</span>
<div class="led"></div>
</div>
<div class="keys-container">
<!-- 白键区 -->
<div class="white-keys" id="whiteKeysContainer">
<!-- 通过 JS 生成,但也可以硬编码,为了整洁用 JS 生成 -->
</div>
<!-- 黑键区 -->
<div class="black-keys-container">
<div class="black-keys" id="blackKeysContainer">
<!-- 动态生成 -->
</div>
</div>
</div>
<div class="footer-plate">仿生立体 · 真实触感</div>
</div>
</div>
<script>
(function() {
// 音频上下文与预加载
let audioCtx = null;
let masterGain = null;
// 音色参数
const activeOscillators = new Map(); // 用于追踪按键对应的振荡器,解决音尾释放
// 初始化音频上下文(在用户首次交互时)
function initAudio() {
if (audioCtx) return;
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
masterGain = audioCtx.createGain();
masterGain.gain.value = 0.5; // 整体音量
masterGain.connect(audioCtx.destination);
// 添加一点压缩和立体感?为了“逼真”,加一点轻微的延迟/混响代价太大,保持干净
// 为了丰富谐波,使用多个振荡器叠加
} catch (e) {
console.warn("Web Audio API 不支持");
}
}
// 频率映射 (从 C4 到 B5,两个八度,实际白键14个,黑键10个)
// 白键:C4 D4 E4 F4 G4 A4 B4 C5 D5 E5 F5 G5 A5 B5 (14个)
// 黑键:C#4 D#4 F#4 G#4 A#4 C#5 D#5 F#5 G#5 A#5 (10个)
const whiteNotes = [
{ note: 'C4', freq: 261.63, label: 'C' },
{ note: 'D4', freq: 293.66, label: 'D' },
{ note: 'E4', freq: 329.63, label: 'E' },
{ note: 'F4', freq: 349.23, label: 'F' },
{ note: 'G4', freq: 392.00, label: 'G' },
{ note: 'A4', freq: 440.00, label: 'A' },
{ note: 'B4', freq: 493.88, label: 'B' },
{ note: 'C5', freq: 523.25, label: 'C' },
{ note: 'D5', freq: 587.33, label: 'D' },
{ note: 'E5', freq: 659.25, label: 'E' },
{ note: 'F5', freq: 698.46, label: 'F' },
{ note: 'G5', freq: 783.99, label: 'G' },
{ note: 'A5', freq: 880.00, label: 'A' },
{ note: 'B5', freq: 987.77, label: 'B' }
];
// 黑键:对应白键之间的位置,用索引表示相对于白键
// 每个黑键指定其左侧白键的索引(从0开始),以及频率和名称
const blackNotes = [
{ leftWhiteIndex: 0, note: 'C#4', freq: 277.18, label: 'C#' }, // C#4 在 C4 和 D4 之间
{ leftWhiteIndex: 1, note: 'D#4', freq: 311.13, label: 'D#' }, // D#4 在 D4 和 E4 之间
{ leftWhiteIndex: 3, note: 'F#4', freq: 369.99, label: 'F#' }, // F#4 在 F4 和 G4 之间
{ leftWhiteIndex: 4, note: 'G#4', freq: 415.30, label: 'G#' }, // G#4 在 G4 和 A4 之间
{ leftWhiteIndex: 5, note: 'A#4', freq: 466.16, label: 'A#' }, // A#4 在 A4 和 B4 之间
{ leftWhiteIndex: 7, note: 'C#5', freq: 554.37, label: 'C#' }, // C#5 在 C5 和 D5 之间
{ leftWhiteIndex: 8, note: 'D#5', freq: 622.25, label: 'D#' }, // D#5 在 D5 和 E5 之间
{ leftWhiteIndex: 10, note: 'F#5', freq: 739.99, label: 'F#' }, // F#5 在 F5 和 G5 之间
{ leftWhiteIndex: 11, note: 'G#5', freq: 830.61, label: 'G#' }, // G#5 在 G5 和 A5 之间
{ leftWhiteIndex: 12, note: 'A#5', freq: 932.33, label: 'A#' } // A#5 在 A5 和 B5 之间
];
// 创建钢琴键 DOM
const whiteContainer = document.getElementById('whiteKeysContainer');
const blackContainer = document.getElementById('blackKeysContainer');
// 存储所有键的DOM引用以便之后键盘映射
const whiteKeyElements = [];
const blackKeyElements = [];
// 生成白键
whiteNotes.forEach((noteObj, index) => {
const key = document.createElement('div');
key.className = 'white-key';
key.dataset.index = index;
key.dataset.note = noteObj.note;
key.dataset.freq = noteObj.freq;
key.dataset.type = 'white';
key.innerHTML = `<span class="key-label">${noteObj.label}</span>`;
whiteContainer.appendChild(key);
whiteKeyElements.push(key);
});
// 生成黑键,使用绝对定位的容器按索引偏移
// 为简化布局,将黑键全部放入 blackKeysContainer,并通过 margin-left 和 flex 定位。
// 但为了精确对齐,使用绝对定位更可靠,但当前 flex + margin 也能实现对齐(通过padding和margin计算)
// 由于白键宽度固定,我们重新计算:每个白键宽58px,gap 2px,总宽60px。
// 黑键宽度36px,需要相对于左侧白键的右边缘偏移 (58 - 36/2) = 40px? 更精确: 黑键中心应在两个白键交界处。
// 实际需要动态计算,为了简化并确保对齐,改用绝对定位方案?但保持flex+margin调整比较麻烦。
// 转换方案:使用绝对定位动态计算每个黑键位置,更加可靠,并适应移动端。
// 重构:改为绝对定位黑键
// 移除原来的black-keys容器样式,直接动态生成绝对定位黑键到blackKeysContainer父级
// 获取父级黑键容器(绝对定位层)
const blackKeysWrapper = document.querySelector('.black-keys-container');
// 清空原有内容
blackKeysWrapper.innerHTML = '';
// 修改样式,允许绝对定位
blackKeysWrapper.style.position = 'absolute';
blackKeysWrapper.style.pointerEvents = 'none';
// 计算每个白键的宽度和间距,用于黑键定位 (JS动态获取白键样式,确保准确)
// 但白键宽度固定,可以写死,但为了响应式,需要在resize时重新计算?简单起见,先以固定宽度计算,加媒体查询适配。
// 为了简化,黑键也使用flex? 放弃,使用绝对定位,根据白键宽度动态计算。
// 获取白键元素的实际宽度和间距
function getWhiteKeyMetrics() {
const firstWhite = whiteKeyElements[0];
if (!firstWhite) return { width: 58, gap: 2, total: 60 };
const style = window.getComputedStyle(firstWhite);
// 获取实际像素宽度,由于可能会有缩放,用getBoundingClientRect更准确
const rect = firstWhite.getBoundingClientRect();
const width = rect.width;
// 计算gap:相邻两个白键左边距差 - 宽度
if (whiteKeyElements.length > 1) {
const rect2 = whiteKeyElements[1].getBoundingClientRect();
const gap = rect2.left - rect.left - width;
return { width, gap, total: width + gap };
}
return { width: 58, gap: 2, total: 60 };
}
// 生成黑键绝对定位
function renderBlackKeys() {
// 清空
blackKeysWrapper.innerHTML = '';
const { width: whiteWidth, gap: whiteGap, total: whiteTotal } = getWhiteKeyMetrics();
// 黑键宽度取白键的0.6左右? 用36px固定,但也要响应式,根据白宽计算
const blackWidth = whiteWidth * 0.62;
// 黑键高度
const containerHeight = blackKeysWrapper.clientHeight;
// 黑键应该比白键短,通常约为黑键的60%~65%高度,但实际由CSS限制,我们设置高度固定,但动态计算也可以
// 为了简单,使用CSS类控制高度,但定位需要left偏移。
// 获取容器左边距:黑键容器相对于keys-container的左边距
// 但黑键容器是absolute定位在keys-container内的,left:0,所以黑键的left直接相对于keys-container。
// 白键容器有padding: 6px 0 0; 还有keys-container padding: 0 6px; 所以白键起始位置有偏移。
const keysContainer = document.querySelector('.keys-container');
const keysRect = keysContainer.getBoundingClientRect();
const whiteKeysContainer = document.querySelector('.white-keys');
const whiteRect = whiteKeysContainer.getBoundingClientRect();
// 第一个白键的左侧距离 keys-container 左边界
const firstWhiteLeft = whiteRect.left - keysRect.left;
// 每个黑键的位置:位于左侧白键的右边缘减去一半黑键宽度,或者使用交界处
blackNotes.forEach((blackNote) => {
const leftWhiteIdx = blackNote.leftWhiteIndex;
// 找到对应的白键元素
const leftWhiteEl = whiteKeyElements[leftWhiteIdx];
if (!leftWhiteEl) return;
const leftWhiteRect = leftWhiteEl.getBoundingClientRect();
// 黑键中心应该位于左白键的右边缘处 (即左白键右侧 + 白键间距/2? 实际上应该正好在两白键之间)
// 更多钢琴:黑键中心在左侧白键的右边和右侧白键左边之间,即交界线。
// 用左白键的右边缘 + gap/2 得到交界线
let blackLeft = leftWhiteRect.right - keysRect.left + (whiteGap / 2) - (blackWidth / 2);
// 限制在黑键容器内可见
// 创建黑键元素
const blackKey = document.createElement('div');
blackKey.className = 'black-key';
blackKey.style.position = 'absolute';
blackKey.style.left = `${blackLeft}px`;
blackKey.style.top = '0px'; // 相对于黑键容器
blackKey.style.width = `${blackWidth}px`;
// 高度由CSS决定,但我们可以动态设置高度为白键高度的60% 左右
const whiteHeight = whiteKeyElements[0]?.getBoundingClientRect().height || 210;
const blackHeight = Math.max(80, whiteHeight * 0.63);
blackKey.style.height = `${blackHeight}px`;
blackKey.dataset.freq = blackNote.freq;
blackKey.dataset.note = blackNote.note;
blackKey.dataset.type = 'black';
blackKey.innerHTML = `<span class="key-label" style="bottom:6px; font-size:9px;">${blackNote.label}</span>`;
// 为黑键添加事件监听(后续统一添加)
blackKey.addEventListener('mousedown', keyDownHandler);
blackKey.addEventListener('mouseup', keyUpHandler);
blackKey.addEventListener('mouseleave', keyUpHandler);
// 触摸支持
blackKey.addEventListener('touchstart', (e) => { e.preventDefault(); keyDownHandler(e); }, { passive: false });
blackKey.addEventListener('touchend', (e) => { e.preventDefault(); keyUpHandler(e); });
blackKey.addEventListener('touchcancel', keyUpHandler);
blackKeysWrapper.appendChild(blackKey);
blackKeyElements.push(blackKey);
});
}
// 音色合成器:使用多个振荡器 + 包络,产生逼真钢琴/电子琴声音
function playNote(freq, velocity = 1.0) {
if (!audioCtx) return;
// 主增益已有,创建独立的增益包络
const now = audioCtx.currentTime;
const gainNode = audioCtx.createGain();
gainNode.connect(masterGain);
// 钢琴/电钢琴般的声音:正弦波+三角波+少许方波,快速起音,衰减
const osc1 = audioCtx.createOscillator(); // 主音正弦
const osc2 = audioCtx.createOscillator(); // 高八度轻微
const osc3 = audioCtx.createOscillator(); // 低八度增加厚度
osc1.type = 'sine';
osc2.type = 'triangle';
osc3.type = 'sine';
// 频率设置
osc1.frequency.value = freq;
osc2.frequency.value = freq * 2.001; // 轻微失谐更真实
osc3.frequency.value = freq * 0.501; // 低八度
// 增益混合
const mix1 = audioCtx.createGain();
const mix2 = audioCtx.createGain();
const mix3 = audioCtx.createGain();
mix1.gain.value = 0.6;
mix2.gain.value = 0.2;
mix3.gain.value = 0.15;
osc1.connect(mix1).connect(gainNode);
osc2.connect(mix2).connect(gainNode);
osc3.connect(mix3).connect(gainNode);
// 包络:攻击快,衰减适中
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(0.8 * velocity, now + 0.02); // 快起音
gainNode.gain.exponentialRampToValueAtTime(0.3 * velocity, now + 0.5);
gainNode.gain.exponentialRampToValueAtTime(0.001, now + 1.2); // 衰减到几乎无声
osc1.start(now);
osc2.start(now);
osc3.start(now);
// 自动停止及清理
const stopTime = now + 1.5;
osc1.stop(stopTime);
osc2.stop(stopTime);
osc3.stop(stopTime);
// 存储以便紧急停止?暂时不实现,让它们自然衰减。
// 但为了按键释放时停止声音?如果按住不放,声音会一直持续到包络结束,但钢琴通常是持续音。
// 这里我们设定即使按住不放,1.2秒后也衰减到几乎无声,符合钢琴特点。
// 如果用户快速点击,会触发多个包络,产生重叠音,这是正常的。
// 为了释放按键时停止声音(比如按住后释放),我们需要追踪当前的增益包络并提前释放?
// 对于仿真钢琴,通常让声音自然衰减更好。但我们也可以提供轻微的按键释放衰减。
// 为了更好的用户体验,如果用户按住不放,我们允许持续发声(但由于包络已经衰减,听起来会变弱)。
// 对于电子琴,通常持续按住会持续发声,所以不能衰减到0。这里为了仿真钢琴,采用自然衰减。
// 但是按住不放就会慢慢消失。考虑到电子琴,改为更长的持续?改成三角钢琴的感觉。
// 调整包络:起音后保持一定音量更长时间,然后缓慢衰减。
// 重新调整:
gainNode.gain.cancelScheduledValues(now);
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(0.9 * velocity, now + 0.02);
gainNode.gain.setTargetAtTime(0.6 * velocity, now + 0.02, 0.3); // 保持
gainNode.gain.setTargetAtTime(0.002, now + 0.8, 0.5); // 1秒后开始衰减
// 记录当前振荡器以便可能的stop? 不做了。
}
// 键盘事件与鼠标事件处理
function keyDownHandler(e) {
const keyEl = e.currentTarget;
// 防止重复触发(鼠标和触摸可能重复)
if (keyEl.classList.contains('active')) return;
keyEl.classList.add('active');
// 初始化音频上下文(必须在用户手势内)
if (!audioCtx) {
initAudio();
}
if (audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume();
}
const freq = parseFloat(keyEl.dataset.freq);
if (!isNaN(freq)) {
playNote(freq, 1.0);
}
e.preventDefault();
}
function keyUpHandler(e) {
const keyEl = e.currentTarget;
keyEl.classList.remove('active');
e.preventDefault();
}
// 为白键绑定事件(在生成时已绑定?没有,生成白键时还未绑定,我们统一在生成后绑定)
function attachWhiteKeyEvents() {
whiteKeyElements.forEach(key => {
// 移除可能已存在的监听,避免重复
key.removeEventListener('mousedown', keyDownHandler);
key.removeEventListener('mouseup', keyUpHandler);
key.removeEventListener('mouseleave', keyUpHandler);
key.removeEventListener('touchstart', keyDownHandler);
key.removeEventListener('touchend', keyUpHandler);
key.removeEventListener('touchcancel', keyUpHandler);
// 添加监听
key.addEventListener('mousedown', keyDownHandler);
key.addEventListener('mouseup', keyUpHandler);
key.addEventListener('mouseleave', keyUpHandler);
key.addEventListener('touchstart', (e) => { e.preventDefault(); keyDownHandler(e); }, { passive: false });
key.addEventListener('touchend', (e) => { e.preventDefault(); keyUpHandler(e); });
key.addEventListener('touchcancel', keyUpHandler);
});
}
// 键盘映射: 电脑键盘弹奏 (两排)
const keyMap = {
// 低八度 C4~B4
'a': 'C4', 'w': 'C#4', 's': 'D4', 'e': 'D#4', 'd': 'E4', 'f': 'F4',
't': 'F#4', 'g': 'G4', 'y': 'G#4', 'h': 'A4', 'u': 'A#4', 'j': 'B4',
// 高八度 C5~B5
'k': 'C5', 'o': 'C#5', 'l': 'D5', 'p': 'D#5', ';': 'E5', "'": 'F5',
']': 'F#5', '\\': 'G5', // 部分键盘布局偏移,为简化,用传统映射
// 也可以加数字键但略过
};
// 更准确的映射:用第二行映射高八度
const preciseKeyMap = {
'a': 'C4', 'w': 'C#4', 's': 'D4', 'e': 'D#4', 'd': 'E4', 'f': 'F4',
't': 'F#4', 'g': 'G4', 'y': 'G#4', 'h': 'A4', 'u': 'A#4', 'j': 'B4',
'k': 'C5', 'o': 'C#5', 'l': 'D5', 'p': 'D#5', ';': 'E5', "'": 'F5',
// 缺少 F#5 等,使用其他键
'z': 'F#5', 'x': 'G5', 'c': 'G#5', 'v': 'A5', 'b': 'A#5', 'n': 'B5'
};
// 用noteName查找元素
function findKeyElementByNote(noteName) {
// 查找白键
for (let el of whiteKeyElements) {
if (el.dataset.note === noteName) return el;
}
for (let el of blackKeyElements) {
if (el.dataset.note === noteName) return el;
}
return null;
}
// 全局键盘按下
function handleKeyDown(e) {
const key = e.key.toLowerCase();
if (e.repeat) return; // 忽略重复触发
const noteName = preciseKeyMap[key];
if (!noteName) return;
const keyEl = findKeyElementByNote(noteName);
if (keyEl && !keyEl.classList.contains('active')) {
keyEl.classList.add('active');
if (!audioCtx) initAudio();
if (audioCtx && audioCtx.state === 'suspended') audioCtx.resume();
const freq = parseFloat(keyEl.dataset.freq);
if (!isNaN(freq)) playNote(freq, 1.0);
}
// 防止页面滚动等
if (key === ' ') e.preventDefault();
}
function handleKeyUp(e) {
const key = e.key.toLowerCase();
const noteName = preciseKeyMap[key];
if (!noteName) return;
const keyEl = findKeyElementByNote(noteName);
if (keyEl) {
keyEl.classList.remove('active');
}
}
// 初始化
function init() {
// 黑键动态渲染(依赖于白键尺寸)
// 先确保白键已经在DOM中,且布局完成
setTimeout(() => {
renderBlackKeys();
// 为白键绑定事件
attachWhiteKeyEvents();
// 为动态生成的黑键绑定事件已经包含在renderBlackKeys内
}, 20);
// 监听窗口大小变化,重新计算黑键位置
window.addEventListener('resize', () => {
// 清除黑键并把旧的引用移除
blackKeyElements.length = 0; // 清空数组
renderBlackKeys();
});
// 键盘事件
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
// 防止触摸时页面缩放/滚动
document.querySelectorAll('.white-key, .black-key').forEach(el => {
el.addEventListener('touchstart', (e) => e.preventDefault(), { passive: false });
});
}
// 页面加载完成初始化
window.addEventListener('load', init);
// 提前初始化音频上下文(但需要用户手势,所以第一次点击任意键时初始化)
})();
</script>
</body>
</html>
```
### 弹奏体验与核心机制
您可以通过鼠标点击或电脑键盘来弹奏钢琴,每个琴键都对应着真实的音高。为了让声音更逼真,代码使用了多层波形合成技术。
- **弹奏方式**:直接用鼠标点击琴键即可发声。同时,您也可以使用电脑键盘,低八度对应字母区(A到J等),高八度对应K到N等键位,具体映射可以参考代码中的`preciseKeyMap`。
- **声音合成**:每个音符的声音都由三个不同频率和波形的振荡器混合而成(正弦波、三角波和低八度正弦波),并配合快速的起音和自然的衰减包络,模拟了钢琴的听感。
- **视觉反馈**:琴键被按下时会有下沉和颜色变化的效果,同时整体琴架带有微妙的3D透视和光影,增强了立体感和操作的真实感。查看完整源码
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Virtuoso | 3D Web Synthesizer</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Inter:wght@300;500&display=swap" rel="stylesheet">
<style>
:root {
--key-white: #fffff0;
--key-black: #1a1a1a;
--wood-dark: #2d1b0e;
--wood-light: #4a3728;
--led-on: #00ffcc;
--led-off: #333;
--bg-color: #111;
}
body {
background-color: var(--bg-color);
background-image: radial-gradient(circle at 50% 50%, #1a1a1a 0%, #000 100%);
font-family: 'Inter', sans-serif;
overflow: hidden;
user-select: none;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* --- 3D Synthesizer Chassis --- */
.synth-chassis {
background: linear-gradient(180deg, #2b2b2b 0%, #1a1a1a 100%);
box-shadow:
0 20px 50px rgba(0,0,0,0.8),
inset 0 1px 0 rgba(255,255,255,0.1);
border-radius: 12px;
padding: 20px;
position: relative;
width: 90%;
max-width: 1000px;
perspective: 1000px;
border-top: 1px solid #444;
border-bottom: 1px solid #000;
}
.wood-panel {
background: repeating-linear-gradient(90deg, var(--wood-dark), var(--wood-light) 10px, var(--wood-dark) 20px);
height: 150px;
margin-bottom: 20px;
border-radius: 4px;
box-shadow: inset 0 5px 15px rgba(0,0,0,0.6);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 30px;
position: relative;
overflow: hidden;
}
.wood-panel::after {
content: '';
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
background: linear-gradient(180deg, rgba(0,0,0,0.2) 0%, transparent 50%, rgba(0,0,0,0.4) 100%);
pointer-events: none;
}
/* --- Controls & Knobs --- */
.knob-container {
display: flex;
flex-direction: column;
align-items: center;
z-index: 2;
}
.knob-label {
color: #aaa;
font-size: 0.7rem;
margin-top: 5px;
text-transform: uppercase;
letter-spacing: 1px;
}
.knob {
width: 50px;
height: 50px;
border-radius: 50%;
background: conic-gradient(#333 0%, #111 100%);
box-shadow: 0 4px 10px rgba(0,0,0,0.5), inset 0 1px 2px rgba(255,255,255,0.1);
position: relative;
cursor: ns-resize;
}
.knob::before {
content: '';
position: absolute;
top: 5px;
left: 50%;
transform: translateX(-50%);
width: 4px;
height: 15px;
background: #00ffcc;
border-radius: 2px;
}
/* --- Keys Area --- */
.keys-container {
position: relative;
height: 280px;
display: flex;
justify-content: center;
background: #000;
padding: 10px 5px 0 5px;
border-radius: 0 0 8px 8px;
box-shadow: inset 0 10px 20px rgba(0,0,0,0.8);
}
/* White Key */
.key-white {
width: 60px;
height: 260px;
background: linear-gradient(to bottom, #fff 0%, #eee 100%);
border-radius: 0 0 4px 4px;
border-left: 1px solid #ccc;
border-bottom: 4px solid #ccc;
position: relative;
z-index: 1;
cursor: pointer;
transform-origin: top;
transition: transform 0.1s, background 0.1s, border-bottom 0.1s;
box-shadow: inset 0 -5px 10px rgba(0,0,0,0.1);
}
.key-white:active, .key-white.active {
background: linear-gradient(to bottom, #f0f0f0 0%, #ddd 100%);
border-bottom: 1px solid #999;
transform: rotateX(-5deg) scale(0.99);
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
/* Black Key */
.key-black {
width: 36px;
height: 160px;
background: linear-gradient(to bottom, #333 0%, #000 100%);
border-radius: 0 0 3px 3px;
position: absolute;
z-index: 2;
top: 10px; /* Offset from top padding */
cursor: pointer;
border-bottom: 4px solid #000;
border-left: 1px solid #444;
border-right: 1px solid #444;
transform-origin: top;
transition: transform 0.1s, background 0.1s;
box-shadow: 2px 5px 10px rgba(0,0,0,0.5);
}
.key-black:active, .key-black.active {
background: linear-gradient(to bottom, #222 0%, #000 100%);
border-bottom: 1px solid #000;
transform: rotateX(-5deg) scale(0.98);
box-shadow: 1px 2px 5px rgba(0,0,0,0.5);
}
/* --- Visualizer & Branding --- */
.visualizer {
width: 300px;
height: 80px;
background: #000;
border: 2px solid #333;
border-radius: 4px;
box-shadow: inset 0 0 10px rgba(0,0,0,1);
position: relative;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
filter: drop-shadow(0 0 5px var(--led-on));
}
.brand-text {
font-family: 'Orbitron', sans-serif;
color: #fff;
font-size: 1.5rem;
letter-spacing: 2px;
text-shadow: 0 0 10px var(--led-on);
}
.power-btn {
width: 30px;
height: 30px;
border-radius: 50%;
background: #333;
border: 2px solid #111;
cursor: pointer;
box-shadow: 0 0 5px rgba(0,0,0,0.5);
transition: all 0.3s;
}
.power-btn.on {
background: #00ffcc;
box-shadow: 0 0 15px #00ffcc;
}
/* Decorational Elements */
.screw {
width: 8px;
height: 8px;
background: #111;
border-radius: 50%;
position: absolute;
box-shadow: inset 0 1px 2px rgba(255,255,255,0.2);
}
.tl { top: 10px; left: 10px; }
.tr { top: 10px; right: 10px; }
.bl { bottom: 10px; left: 10px; }
.br { bottom: 10px; right: 10px; }
/* Particle Effects */
.particle {
position: absolute;
pointer-events: none;
background: var(--led-on);
border-radius: 50%;
animation: floatUp 1s ease-out forwards;
}
@keyframes floatUp {
0% { transform: translateY(0) scale(1); opacity: 1; }
100% { transform: translateY(-50px) scale(0); opacity: 0; }
}
.overlay {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.8);
display: flex;
justify-content: center;
align-items: center;
z-index: 100;
backdrop-filter: blur(5px);
transition: opacity 0.5s;
}
.hidden-overlay {
opacity: 0;
pointer-events: none;
}
</style>
</head>
<body>
<!-- Start Overlay -->
<div id="startOverlay" class="overlay">
<div class="text-center">
<h1 class="text-5xl font-bold text-white mb-4 font-[Orbitron] tracking-widest">VIRTUOSO</h1>
<p class="text-gray-400 mb-8">Professional Web Audio Synthesizer</p>
<button id="startBtn" class="px-8 py-3 bg-transparent border-2 border-[#00ffcc] text-[#00ffcc] font-bold rounded hover:bg-[#00ffcc] hover:text-black transition-all uppercase tracking-widest">
Click to Power On
</button>
<p class="text-xs text-gray-600 mt-4">Headphones Recommended</p>
</div>
</div>
<!-- Main Synth Body -->
<div class="synth-chassis">
<!-- Screws for realism -->
<div class="screw tl"></div><div class="screw tr"></div>
<div class="screw bl"></div><div class="screw br"></div>
<!-- Control Panel -->
<div class="wood-panel">
<!-- Branding -->
<div class="z-10">
<div class="brand-text">VIRTUOSO</div>
<div class="text-xs text-gray-400 tracking-widest">POLYPHONIC SYNTHESIZER</div>
</div>
<!-- Visualizer -->
<div class="visualizer z-10">
<canvas id="visualizerCanvas"></canvas>
</div>
<!-- Controls -->
<div class="flex gap-6 z-10">
<div class="knob-container">
<div class="knob" id="volumeKnob" style="transform: rotate(-45deg);"></div>
<div class="knob-label">Master Vol</div>
</div>
<div class="knob-container">
<div class="knob" id="detuneKnob" style="transform: rotate(0deg);"></div>
<div class="knob-label">Detune</div>
</div>
<div class="flex flex-col items-center justify-center ml-4">
<div class="power-btn on" id="powerBtn"></div>
<div class="knob-label mt-2">Power</div>
</div>
</div>
</div>
<!-- Keyboard Area -->
<div class="keys-container" id="keyboard">
<!-- Keys will be generated by JS -->
</div>
</div>
<!-- Instructions -->
<div class="mt-8 text-gray-500 text-sm font-mono text-center">
<p>Keyboard: [A] [S] [D] [F] [G] [H] [J] [K] [L] [;]</p>
<p>Black Keys: [W] [E] [T] [Y] [U] [O] [P]</p>
</div>
<script>
// --- Configuration & State ---
const notes = [
{ note: 'C3', type: 'white', key: 'z' },
{ note: 'C#3', type: 'black', key: 's' },
{ note: 'D3', type: 'white', key: 'x' },
{ note: 'D#3', type: 'black', key: 'd' },
{ note: 'E3', type: 'white', key: 'c' },
{ note: 'F3', type: 'white', key: 'v' },
{ note: 'F#3', type: 'black', key: 'g' },
{ note: 'G3', type: 'white', key: 'b' },
{ note: 'G#3', type: 'black', key: 'h' },
{ note: 'A3', type: 'white', key: 'n' },
{ note: 'A#3', type: 'black', key: 'j' },
{ note: 'B3', type: 'white', key: 'm' },
{ note: 'C4', type: 'white', key: 'q' }, // Middle C mapped to Q or Comma - let's use row 2
{ note: 'C4', type: 'white', key: ',' },
{ note: 'C#4', type: 'black', key: '2' },
{ note: 'C#4', type: 'black', key: 'l' },
{ note: 'D4', type: 'white', key: 'w' },
{ note: 'D4', type: 'white', key: '.' },
{ note: 'D#4', type: 'black', key: '3' },
{ note: 'D#4', type: 'black', key: ';' },
{ note: 'E4', type: 'white', key: 'e' },
{ note: 'E4', type: 'white', key: '/' },
{ note: 'F4', type: 'white', key: 'r' },
{ note: 'F#4', type: 'black', key: '5' },
{ note: 'G4', type: 'white', key: 't' },
{ note: 'G#4', type: 'black', key: '6' },
{ note: 'A4', type: 'white', key: 'y' },
{ note: 'A#4', type: 'black', key: '7' },
{ note: 'B4', type: 'white', key: 'u' },
{ note: 'C5', type: 'white', key: 'i' }
];
// Simplified mapping for the main visible keyboard layout
// We will generate a specific range for the UI.
const keyboardMap = [
{ note: 'C3', key: 'z', type: 'white' },
{ note: 'C#3', key: 's', type: 'black' },
{ note: 'D3', key: 'x', type: 'white' },
{ note: 'D#3', key: 'd', type: 'black' },
{ note: 'E3', key: 'c', type: 'white' },
{ note: 'F3', key: 'v', type: 'white' },
{ note: 'F#3', key: 'g', type: 'black' },
{ note: 'G3', key: 'b', type: 'white' },
{ note: 'G#3', key: 'h', type: 'black' },
{ note: 'A3', key: 'n', type: 'white' },
{ note: 'A#3', key: 'j', type: 'black' },
{ note: 'B3', key: 'm', type: 'white' },
{ note: 'C4', key: 'q', type: 'white' }, // Using top row for higher octave overlap
{ note: 'C#4', key: '2', type: 'black' },
{ note: 'D4', key: 'w', type: 'white' },
{ note: 'D#4', key: '3', type: 'black' },
{ note: 'E4', key: 'e', type: 'white' },
{ note: 'F4', key: 'r', type: 'white' },
{ note: 'F#4', key: '5', type: 'black' },
{ note: 'G4', key: 't', type: 'white' },
{ note: 'G#4', key: '6', type: 'black' },
{ note: 'A4', key: 'y', type: 'white' },
{ note: 'A#4', key: '7', type: 'black' },
{ note: 'B4', key: 'u', type: 'white' },
{ note: 'C5', key: 'i', type: 'white' }
];
let synth;
let reverb;
let delay;
let analyser;
let isPowerOn = false;
let activeNotes = new Set();
// --- Initialization ---
const startBtn = document.getElementById('startBtn');
const overlay = document.getElementById('startOverlay');
startBtn.addEventListener('click', async () => {
await Tone.start();
initAudio();
overlay.classList.add('hidden-overlay');
isPowerOn = true;
animateVisualizer();
});
function initAudio() {
// Create a PolySynth for chords
synth = new Tone.PolySynth(Tone.Synth, {
oscillator: {
type: "triangle" // Warm sound
},
envelope: {
attack: 0.005,
decay: 0.1,
sustain: 0.3,
release: 1
}
});
// Effects Chain
reverb = new Tone.Reverb({ decay: 2, wet: 0.2 }).toDestination();
delay = new Tone.FeedbackDelay("8n", 0.1).connect(reverb);
// Analyser for visualizer
analyser = new Tone.Analyser("waveform", 256);
synth.connect(delay);
synth.connect(analyser); // Connect to analyser for visual
// Initial Volume
synth.volume.value = -10;
}
// --- UI Generation ---
const keyboardEl = document.getElementById('keyboard');
const keyElements = {}; // Map note to DOM element
// Layout logic for positioning black keys
// C, D, E, F, G, A, B
// Black keys are after C, D, F, G, A
function createKeyboard() {
let whiteKeyIndex = 0;
keyboardMap.forEach((k) => {
const keyDiv = document.createElement('div');
keyDiv.dataset.note = k.note;
keyDiv.dataset.key = k.key;
if (k.type === 'white') {
keyDiv.className = 'key-white';
keyboardEl.appendChild(keyDiv);
whiteKeyIndex++;
} else {
keyDiv.className = 'key-black';
// Calculate position based on previous white key
// Simple approximation: Each white key is ~60px.
// Black key sits between them.
// We need to position absolute relative to container.
// Since we are appending in order, we can calculate left % or px.
// Better: Use margin-left trick or absolute positioning.
// Let's use absolute positioning based on index.
// Formula: (WhiteKeyIndex * 60) - (BlackKeyWidth / 2)
// But since container is flex, let's append black keys to container and position absolute
// We need to know the left position.
// Let's refine the render loop.
// We will render ALL white keys first? No, order matters for z-index (black on top).
// Actually, if we put white keys in flow, and black keys absolute:
// Left of black key = (Index of previous white key + 1) * width - (blackWidth/2)
}
});
// Re-approach: Render White keys in flow. Render Black keys absolute on top.
// Filter white and black
const whiteKeys = keyboardMap.filter(k => k.type === 'white');
const blackKeys = keyboardMap.filter(k => k.type === 'black');
// Render White
whiteKeys.forEach(k => {
const div = document.createElement('div');
div.className = 'key-white';
div.id = `key-${k.note}`;
div.dataset.note = k.note;
div.dataset.key = k.key;
// Event Listeners
addInteraction(div, k.note);
keyboardEl.appendChild(div);
keyElements[k.note] = div;
});
// Render Black
// We need to find the X position.
// The container is flex, centered.
// Let's calculate percentage or rely on offset calculation after render.
// Since layout is dynamic, let's use JS to place them after a brief render.
setTimeout(() => {
let whiteIndex = 0;
keyboardMap.forEach(k => {
if(k.type === 'white') whiteIndex++;
if(k.type === 'black') {
// Find the previous white key element
// This is tricky because of the array structure.
// Let's map black keys to their preceding white key note.
// C# is after C.
// Simplified: Just calculate based on index.
// White key width is ~60px (variable).
// Let's place it based on the 'left' property of the previous white key + width.
// Actually, simpler CSS trick:
// Put black keys inside the white keys? No.
// Put black keys absolute.
// The container is relative.
// Left = (Index of previous white key * width of white key) + (width/2)
// Let's find the index of the white key that comes BEFORE this black key.
// e.g. C#3. Previous white is C3.
// In keyboardMap, C3 is index 0. C#3 is index 1.
// We need to know the visual index of the white key.
// Let's count white keys encountered so far.
}
});
}, 0);
}
// Better Rendering Strategy
function renderKeyboard() {
const container = document.getElementById('keyboard');
container.innerHTML = '';
// We will create a container for white keys and a container for black keys overlaid
const whiteContainer = document.createElement('div');
whiteContainer.className = 'flex justify-center w-full h-full relative';
const blackContainer = document.createElement('div');
blackContainer.className = 'absolute top-0 left-0 w-full h-full pointer-events-none'; // pointer-events-none allows clicking through gaps
container.appendChild(whiteContainer);
container.appendChild(blackContainer);
let whiteKeyCount = 0;
const whiteKeyWidth = 60; // Approximate base width
keyboardMap.forEach((k) => {
if (k.type === 'white') {
const div = document.createElement('div');
div.className = 'key-white flex-shrink-0';
div.style.width = `${100/15}%`; // Distribute 15 white keys roughly
div.id = `key-${k.note}`;
div.dataset.note = k.note;
addInteraction(div, k.note);
whiteContainer.appendChild(div);
keyElements[k.note] = div;
whiteKeyCount++;
}
});
// Now place black keys
// We need to know the visual position of the white keys.
// Since they are flex, we can calculate their center points.
// Helper to find center of a white key
const getCenter = (note) => {
const el = document.getElementById(`key-${note}`);
return el ? el.offsetLeft + (el.offsetWidth / 2) : 0;
};
// Delay slightly to ensure DOM layout is calculated
setTimeout(() => {
keyboardMap.forEach((k) => {
if (k.type === 'black') {
// Find preceding white key note
// e.g. C#3 -> C3
const noteBase = k.note.replace('#', '');
const prevNote = noteBase.slice(0, -1) + (parseInt(noteBase.slice(-1)) - (k.note.includes('C#') && noteBase.startsWith('C') ? 0 : 0));
// Simple logic: C#3 follows C3.
// Extract note name and octave
const parts = k.note.match(/([A-G])(#?)(\d)/);
const noteName = parts[1];
const isSharp = parts[2] === '#';
const octave = parts[3];
// Construct preceding white key
let prevNoteName = noteName;
if (noteName === 'C') prevNoteName = 'B';
else if (noteName === 'F') prevNoteName = 'E';
else {
// A# -> A, D# -> D
prevNoteName = String.fromCharCode(noteName.charCodeAt(0) - 1);
}
// Handle Octave wrap for B
let prevOctave = octave;
if (noteName === 'C') prevOctave = (parseInt(octave) - 1).toString();
const prevFullNote = prevNoteName + prevOctave;
const center = getCenter(prevFullNote);
const div = document.createElement('div');
div.className = 'key-black pointer-events-auto';
div.style.left = `${center}px`;
// Adjust width relative to white key
div.style.width = `4%`;
div.style.minWidth = '30px';
div.dataset.note = k.note;
addInteraction(div, k.note);
blackContainer.appendChild(div);
keyElements[k.note] = div;
}
});
}, 50);
}
function addInteraction(element, note) {
const start = (e) => {
if(e.cancelable) e.preventDefault();
playNote(note);
element.classList.add('active');
};
const end = (e) => {
if(e.cancelable) e.preventDefault();
stopNote(note);
element.classList.remove('active');
};
element.addEventListener('mousedown', start);
element.addEventListener('mouseup', end);
element.addEventListener('mouseleave', end);
element.addEventListener('touchstart', start);
element.addEventListener('touchend', end);
}
// --- Audio Logic ---
function playNote(note) {
if (!isPowerOn || !synth) return;
if (activeNotes.has(note)) return; // Prevent re-triggering while holding
synth.triggerAttack(note);
activeNotes.add(note);
triggerVisualEffect(note);
}
function stopNote(note) {
if (!synth) return;
synth.triggerRelease(note);
activeNotes.delete(note);
}
// --- Keyboard Handling ---
window.addEventListener('keydown', (e) => {
if (e.repeat) return;
const noteObj = keyboardMap.find(k => k.key === e.key.toLowerCase());
if (noteObj) {
playNote(noteObj.note);
const el = keyElements[noteObj.note];
if(el) el.classList.add('active');
}
});
window.addEventListener('keyup', (e) => {
const noteObj = keyboardMap.find(k => k.key === e.key.toLowerCase());
if (noteObj) {
stopNote(noteObj.note);
const el = keyElements[noteObj.note];
if(el) el.classList.remove('active');
}
});
// --- Visualizer ---
const canvas = document.getElementById('visualizerCanvas');
const ctx = canvas.getContext('2d');
function animateVisualizer() {
requestAnimationFrame(animateVisualizer);
if (!analyser) return;
const values = analyser.getValue();
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
// Gradient
const gradient = ctx.createLinearGradient(0, 0, width, 0);
gradient.addColorStop(0, '#00ffcc');
gradient.addColorStop(1, '#0088ff');
ctx.strokeStyle = gradient;
ctx.lineWidth = 2;
ctx.beginPath();
const sliceWidth = width * 1.0 / values.length;
let x = 0;
for (let i = 0; i < values.length; i++) {
const v = values[i]; // -1 to 1
const y = (v * 0.8 + 1) / 2 * height; // Scale to fit
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
x += sliceWidth;
}
ctx.stroke();
// Glow effect
ctx.shadowBlur = 10;
ctx.shadowColor = '#00ffcc';
}
// --- Particle Effects ---
function triggerVisualEffect(note) {
const el = keyElements[note];
if (!el) return;
const rect = el.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top;
for (let i = 0; i < 5; i++) {
createParticle(centerX, centerY);
}
}
function createParticle(x, y) {
const p = document.createElement('div');
p.className = 'particle';
const size = Math.random() * 4 + 2;
p.style.width = `${size}px`;
p.style.height = `${size}px`;
p.style.left = `${x + (Math.random() * 20 - 10)}px`;
p.style.top = `${y + (Math.random() * 10)}px`;
document.body.appendChild(p);
setTimeout(() => {
p.remove();
}, 1000);
}
// --- Knobs Logic (Simplified) ---
// Just visual rotation for this demo
const volumeKnob = document.getElementById('volumeKnob');
const detuneKnob = document.getElementById('detuneKnob');
const powerBtn = document.getElementById('powerBtn');
powerBtn.addEventListener('click', () => {
isPowerOn = !isPowerOn;
powerBtn.classList.toggle('on');
if(!isPowerOn && synth) {
synth.releaseAll();
}
});
// Initial Render
renderKeyboard();
// Resize listener to fix black key positions
window.addEventListener('resize', () => {
renderKeyboard();
});
</script>
</body>
</html>
```实现要点
创建一个网页版的电子琴,并且要求声音逼真且外观仿真立体,需要使用HTML、CSS和JavaScript(可能还需要一些音频处理库,如Web Audio API)。以下是一个简单的实现步骤:
1. 设计界面
首先,我们需要设计电子琴的外观。可以使用HTML和CSS来实现。
2. 添加声音
使用Web Audio API来生成和播放声音。
3. 立体效果
要实现立体效果,可以使用CSS 3D变换。
4. 优化和美化
你可以添加更多的功能,如音量控制、和弦、音色选择等,并且可以使用更高级的CSS和JavaScript库来增强视觉效果和用户体验。
这只是一个非常基础的实现。根据你的需求,你可能需要添加更多的键位、音色和功能。希望这个示例能帮助你入门!
查看完整源码
创建一个网页版的电子琴,并且要求声音逼真且外观仿真立体,需要使用HTML、CSS和JavaScript(可能还需要一些音频处理库,如Web Audio API)。以下是一个简单的实现步骤:
### 1. 设计界面
首先,我们需要设计电子琴的外观。可以使用HTML和CSS来实现。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Electronic Piano</title>
<style>
.keyboard {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 300px;
}
.key {
width: 50px;
height: 100px;
background-color: #333;
margin: 5px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
color: white;
font-size: 24px;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="keyboard">
<!-- 键盘键位 -->
<div class="key" data-note="C4"></div>
<div class="key" data-note="D4"></div>
<div class="key" data-note="E4"></div>
<div class="key" data-note="F4"></div>
<div class="key" data-note="G4"></div>
<div class="key" data-note="A4"></div>
<div class="key" data-note="B4"></div>
<div class="key" data-note="C5"></div>
</div>
<script src="piano.js"></script>
</body>
</html>
```
### 2. 添加声音
使用Web Audio API来生成和播放声音。
```javascript
// piano.js
document.addEventListener('DOMContentLoaded', function() {
const keys = document.querySelectorAll('.key');
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
keys.forEach(key => {
key.addEventListener('click', () => {
playNote(key.dataset.note);
});
key.addEventListener('mousedown', () => {
key.classList.add('active');
playNote(key.dataset.note);
});
key.addEventListener('mouseup', () => {
key.classList.remove('active');
stopNote(key.dataset.note);
});
});
function playNote(note) {
const oscillator = audioContext.createOscillator();
oscillator.frequency.setValueAtTime(getFrequency(note), audioContext.currentTime);
oscillator.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.5);
}
function stopNote(note) {
const oscillator = audioContext.createOscillator();
oscillator.frequency.setValueAtTime(getFrequency(note), audioContext.currentTime);
oscillator.connect(audioContext.destination);
oscillator.stop(audioContext.currentTime);
}
function getFrequency(note) {
const noteFrequencies = {
'C4': 261.6,
'D4': 293.7,
'E4': 329.6,
'F4': 349.2,
'G4': 392.0,
'A4': 440.0,
'B4': 493.9,
'C5': 523.3
};
return noteFrequencies[note];
}
});
```
### 3. 立体效果
要实现立体效果,可以使用CSS 3D变换。
```css
.key {
/* ... */
transform: scale(1) rotateX(0deg) rotateY(0deg);
transition: transform 0.2s ease;
}
.key.active {
transform: scale(1.1) rotateX(20deg) rotateY(20deg);
}
```
### 4. 优化和美化
你可以添加更多的功能,如音量控制、和弦、音色选择等,并且可以使用更高级的CSS和JavaScript库来增强视觉效果和用户体验。
这只是一个非常基础的实现。根据你的需求,你可能需要添加更多的键位、音色和功能。希望这个示例能帮助你入门!未产出可运行的网页产物
查看完整源码
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🎹 3D 立体电子琴</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
min-height: 100vh;
background: linear-gradient(135deg, #0a0a1a 0%, #1a1a3e 30%, #2a1a3e 60%, #1a0a2e 100%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: 'Segoe UI', Arial, sans-serif;
overflow: hidden;
position: relative;
}
/* 背景星星 */
body::before {
content: '';
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
background:
radial-gradient(1px 1px at 20% 30%, rgba(255,255,255,0.8), transparent),
radial-gradient(1px 1px at 40% 70%, rgba(255,255,255,0.6), transparent),
radial-gradient(1.5px 1.5px at 60% 20%, rgba(255,255,255,0.9), transparent),
radial-gradient(1px 1px at 80% 50%, rgba(255,255,255,0.7), transparent),
radial-gradient(1px 1px at 10% 80%, rgba(255,255,255,0.5), transparent),
radial-gradient(1.5px 1.5px at 90% 10%, rgba(255,255,255,0.8), transparent),
radial-gradient(1px 1px at 50% 90%, rgba(255,255,255,0.6), transparent),
radial-gradient(1px 1px at 70% 40%, rgba(255,255,255,0.7), transparent);
pointer-events: none;
z-index: 0;
}
.piano-container {
position: relative;
z-index: 1;
transform: perspective(800px) rotateX(8deg);
}
.piano-brand {
text-align: center;
margin-bottom: 15px;
}
.piano-brand h1 {
font-size: 28px;
background: linear-gradient(90deg, #ffd700, #ffaa00, #ffd700);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: none;
letter-spacing: 6px;
text-transform: uppercase;
filter: drop-shadow(0 0 10px rgba(255,215,0,0.3));
}
.piano-brand .subtitle {
color: rgba(255,255,255,0.4);
font-size: 11px;
letter-spacing: 3px;
margin-top: 4px;
}
.piano-body {
background: linear-gradient(180deg, #1a1a1a 0%, #0d0d0d 30%, #1a1a1a 100%);
border-radius: 12px 12px 8px 8px;
padding: 25px 20px 15px;
box-shadow:
0 20px 60px rgba(0,0,0,0.8),
0 0 0 2px rgba(255,255,255,0.05),
inset 0 1px 0 rgba(255,255,255,0.1);
position: relative;
}
.piano-body::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0;
height: 3px;
background: linear-gradient(90deg, transparent, rgba(255,215,0,0.4), transparent);
border-radius: 12px 12px 0 0;
}
.controls-bar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding: 0 5px;
}
.control-group {
display: flex;
align-items: center;
gap: 8px;
}
.control-label {
color: rgba(255,255,255,0.5);
font-size: 11px;
letter-spacing: 1px;
}
.knob {
width: 40px;
height: 40px;
background: radial-gradient(circle at 35% 35%, #555, #222 70%);
border-radius: 50%;
border: 2px solid #333;
box-shadow: 0 2px 8px rgba(0,0,0,0.5), inset 0 1px 2px rgba(255,255,255,0.1);
cursor: pointer;
position: relative;
}
.knob::after {
content: '';
position: absolute;
top: 4px;
left: 50%;
transform: translateX(-50%);
width: 3px;
height: 12px;
background: #ffd700;
border-radius: 2px;
}
.knob:hover {
box-shadow: 0 2px 12px rgba(0,0,0,0.7), inset 0 1px 2px rgba(255,255,255,0.15);
}
.volume-display {
color: #ffd700;
font-size: 12px;
font-weight: bold;
min-width: 30px;
text-align: center;
}
.sustain-btn {
padding: 6px 16px;
background: linear-gradient(180deg, #333, #222);
border: 1px solid #444;
color: #aaa;
border-radius: 6px;
font-size: 11px;
cursor: pointer;
letter-spacing: 1px;
transition: all 0.2s;
}
.sustain-btn.active {
background: linear-gradient(180deg, #5a4a00, #3a2a00);
border-color: #ffd700;
color: #ffd700;
box-shadow: 0 0 10px rgba(255,215,0,0.3);
}
.keys-container {
position: relative;
display: flex;
height: 200px;
user-select: none;
}
.key-wrapper {
position: relative;
flex: 1;
}
.white-key {
position: absolute;
bottom: 0;
left: 2px;
right: 2px;
height: 100%;
background: linear-gradient(180deg,
#f5f5f5 0%,
#ffffff 5%,
#f0f0f0 30%,
#e8e8e8 70%,
#d8d8d8 85%,
#c8c8c8 100%
);
border-radius: 0 0 6px 6px;
cursor: pointer;
box-shadow:
-3px 0 5px rgba(0,0,0,0.2),
3px 0 5px rgba(0,0,0,0.2),
0 4px 8px rgba(0,0,0,0.4),
inset 0 -3px 5px rgba(0,0,0,0.05),
inset 1px 0 0 rgba(255,255,255,0.8),
inset -1px 0 0 rgba(255,255,255,0.8);
transition: all 0.06s ease;
z-index: 1;
}
.white-key:hover {
background: linear-gradient(180deg, #fafafa 0%, #fff 5%, #f5f5f5 30%, #eee 70%, #ddd 85%, #ccc 100%);
}
.white-key.pressed {
background: linear-gradient(180deg, #e0e0e0 0%, #e8e8e8 5%, #ddd 30%, #ccc 70%, #bbb 85%, #aaa 100%);
box-shadow:
-2px 0 3px rgba(0,0,0,0.15),
2px 0 3px rgba(0,0,0,0.15),
0 1px 3px rgba(0,0,0,0.3),
inset 0 2px 4px rgba(0,0,0,0.1);
transform: translateY(3px);
height: calc(100% - 3px) !important;
}
.white-key .note-label {
position: absolute;
bottom: 8px;
left: 50%;
transform: translateX(-50%);
font-size: 9px;
color: #aaa;
font-weight: bold;
pointer-events: none;
}
.white-key .key-label {
position: absolute;
bottom: 22px;
left: 50%;
transform: translateX(-50%);
font-size: 10px;
color: #bbb;
pointer-events: none;
}
.black-key {
position: absolute;
bottom: 0;
left: -10%;
right: -10%;
height: 62%;
background: linear-gradient(180deg,
#2a2a2a 0%,
#1a1a1a 10%,
#111 40%,
#0a0a0a 70%,
#050505 100%
);
border-radius: 0 0 5px 4px;
cursor: pointer;
z-index: 2;
box-shadow:
-4px 0 8px rgba(0,0,0,0.6),
4px 0 8px rgba(0,0,0,0.6),
0 6px 12px rgba(0,0,0,0.7),
inset 0 -4px 6px rgba(0,0,0,0.3),
inset 1px 0 1px rgba(255,255,255,0.1),
inset -1px 0 1px rgba(255,255,255,0.05);
transition: all 0.06s ease;
}
.black-key::before {
content: '';
position: absolute;
top: 0;
left: 3px;
right: 3px;
height: 40%;
background: linear-gradient(180deg, rgba(255,255,255,0.08), transparent);
border-radius: 3px 3px 0 0;
}
.black-key:hover {
background: linear-gradient(180deg, #333 0%, #222 10%, #1a1a1a 40%, #111 70%, #0a0a0a 100%);
}
.black-key.pressed {
background: linear-gradient(180deg, #1a1a1a 0%, #111 10%, #0a0a0a 40%, #050505 70%, #000 100%);
box-shadow:
-2px 0 4px rgba(0,0,0,0.5),
2px 0 4px rgba(0,0,0,0.5),
0 2px 6px rgba(0,0,0,0.6),
inset 0 3px 5px rgba(0,0,0,0.4);
transform: translateY(2px);
height: calc(62% - 2px) !important;
}
.black-key .note-label {
position: absolute;
bottom: 6px;
left: 50%;
transform: translateX(-50%);
font-size: 8px;
color: #666;
font-weight: bold;
pointer-events: none;
}
/* 辉光效果 */
.key-glow {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 30px;
background: radial-gradient(ellipse at center bottom, rgba(255,215,0,0.15), transparent);
pointer-events: none;
opacity: 0;
transition: opacity 0.3s;
z-index: 3;
}
.white-key.pressed .key-glow,
.black-key.pressed .key-glow {
opacity: 1;
}
/* 底部反光条 */
.piano-footer {
display: flex;
justify-content: center;
gap: 3px;
margin-top: 10px;
}
.footer-strip {
width: 60px;
height: 4px;
background: linear-gradient(90deg, transparent, rgba(255,215,0,0.3), transparent);
border-radius: 2px;
}
.info-panel {
position: fixed;
top: 20px;
right: 20px;
background: rgba(0,0,0,0.6);
backdrop-filter: blur(10px);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 10px;
padding: 15px;
color: rgba(255,255,255,0.7);
font-size: 12px;
z-index: 10;
min-width: 200px;
}
.info-panel h3 {
color: #ffd700;
margin-bottom: 8px;
font-size: 13px;
letter-spacing: 2px;
}
.info-panel .key-hint {
display: flex;
justify-content: space-between;
padding: 2px 0;
border-bottom: 1px solid rgba(255,255,255,0.05);
}
.info-panel .key-hint span:first-child {
color: #ffd700;
font-family: monospace;
}
.visualizer {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 3px;
align-items: flex-end;
height: 40px;
z-index: 10;
}
.viz-bar {
width: 4px;
background: linear-gradient(to top, #ffd700, #ff6b00);
border-radius: 2px 2px 0 0;
transition: height 0.15s ease;
min-height: 2px;
}
.octave-selector {
display: flex;
gap: 5px;
align-items: center;
}
.oct-btn {
width: 28px;
height: 28px;
border-radius: 50%;
border: 1px solid #444;
background: linear-gradient(180deg, #333, #222);
color: #aaa;
font-size: 14px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
}
.oct-btn.active {
background: linear-gradient(180deg, #5a4a00, #3a2a00);
border-color: #ffd700;
color: #ffd700;
}
.oct-btn:hover {
border-color: #666;
color: #fff;
}
@media (max-width: 900px) {
.keys-container { height: 140px; }
.info-panel { display: none; }
.piano-brand h1 { font-size: 20px; }
}
</style>
</head>
<body>
<div class="info-panel">
<h3>🎹 键盘映射</h3>
<div class="key-hint"><span>A-L</span><span>白键 C4-C5</span></div>
<div class="key-hint"><span>W E T Y U O P</span><span>黑键</span></div>
<div class="key-hint"><span>Z / X</span><span>低/高八度</span></div>
<div class="key-hint"><span>Space</span><span>延音踏板</span></div>
</div>
<div class="piano-container">
<div class="piano-brand">
<h1>🎹 Grand Piano</h1>
<div class="subtitle">PREMIUM DIGITAL PIANO</div>
</div>
<div class="piano-body">
<div class="controls-bar">
<div class="control-group">
<span class="control-label">🔊 音量</span>
<div class="knob" id="volumeKnob" title="拖动调节音量"></div>
<span class="volume-display" id="volumeDisplay">75</span>
</div>
<div class="control-group">
<span class="control-label">🎵 八度</span>
<div class="octave-selector">
<button class="oct-btn" id="octDown" title="降低八度">−</button>
<button class="oct-btn active" id="octCur" title="当前八度">4</button>
<button class="oct-btn" id="octUp" title="升高八度">+</button>
</div>
</div>
<div class="control-group">
<span class="control-label">🎛️ 延音</span>
<button class="sustain-btn" id="sustainBtn">SUSTAIN</button>
</div>
</div>
<div class="keys-container" id="keysContainer"></div>
<div class="piano-footer">
<div class="footer-strip"></div>
<div class="footer-strip"></div>
<div class="footer-strip"></div>
</div>
</div>
</div>
<div class="visualizer" id="visualizer"></div>
<script>
// ===== 音频引擎 =====
let audioCtx = null;
let masterGain = null;
let analyser = null;
let currentOctave = 4;
let sustainOn = false;
let sustainedNotes = [];
let volume = 0.75;
function initAudio() {
if (audioCtx) return;
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
masterGain = audioCtx.createGain();
masterGain.gain.value = volume;
analyser = audioCtx.createAnalyser();
analyser.fftSize = 64;
masterGain.connect(analyser);
analyser.connect(audioCtx.destination);
}
// 钢琴音色合成 - 多谐波+快速衰减模拟真实钢琴
function playPianoNote(frequency, duration = 3) {
if (!audioCtx) initAudio();
const now = audioCtx.currentTime;
const noteGain = audioCtx.createGain();
// 主音量包络 - 快速起音 + 衰减
noteGain.gain.setValueAtTime(0, now);
noteGain.gain.linearRampToValueAtTime(0.8, now + 0.005);
noteGain.gain.exponentialRampToValueAtTime(0.3, now + 0.08);
noteGain.gain.exponentialRampToValueAtTime(0.15, now + 0.3);
noteGain.gain.exponentialRampToValueAtTime(0.05, now + 1.5);
noteGain.gain.exponentialRampToValueAtTime(0.001, now + duration);
noteGain.connect(masterGain);
// 谐波1 - 基频
const osc1 = audioCtx.createOscillator();
const gain1 = audioCtx.createGain();
osc1.type = 'sine';
osc1.frequency.value = frequency;
gain1.gain.value = 1.0;
osc1.connect(gain1);
gain1.connect(noteGain);
// 谐波2 - 2倍频 (柔和)
const osc2 = audioCtx.createOscillator();
const gain2 = audioCtx.createGain();
osc2.type = 'sine';
osc2.frequency.value = frequency * 2;
gain2.gain.setValueAtTime(0.3, now);
gain2.gain.exponentialRampToValueAtTime(0.05, now + 0.5);
osc2.connect(gain2);
gain2.connect(noteGain);
// 谐波3 - 3倍频 (亮度)
const osc3 = audioCtx.createOscillator();
const gain3 = audioCtx.createGain();
osc3.type = 'sine';
osc3.frequency.value = frequency * 3;
gain3.gain.setValueAtTime(0.15, now);
gain3.gain.exponentialRampToValueAtTime(0.02, now + 0.3);
osc3.connect(gain3);
gain3.connect(noteGain);
// 谐波4 - 非谐和泛音 (击弦感)
const osc4 = audioCtx.createOscillator();
const gain4 = audioCtx.createGain();
osc4.type = 'triangle';
osc4.frequency.value = frequency * 4.2;
gain4.gain.setValueAtTime(0.08, now);
gain4.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
osc4.connect(gain4);
gain4.connect(noteGain);
// 轻微失谐模拟真实弦
const osc5 = audioCtx.createOscillator();
const gain5 = audioCtx.createGain();
osc5.type = 'sine';
osc5.frequency.value = frequency * 1.001;
gain5.gain.value = 0.1;
osc5.connect(gain5);
gain5.connect(noteGain);
// 所有振荡器启动和停止
[osc1, osc2, osc3, osc4, osc5].forEach(o => {
o.start(now);
o.stop(now + duration + 0.1);
});
// 记录音符用于延音
if (sustainOn) {
sustainedNotes.push({ gain: noteGain, oscs: [osc1,osc2,osc3,osc4,osc5], stopTime: now + duration });
}
}
function stopSustainedNotes() {
sustainedNotes.forEach(n => {
if (n.gain) n.gain.gain.setValueAtTime(0, audioCtx.currentTime);
if (n.oscs) n.oscs.forEach(o => o.stop(audioCtx.currentTime + 0.05));
});
sustainedNotes = [];
}
// ===== 键盘生成 =====
const NOTE_NAMES = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
const BLACK_INDICES = [1,3,6,8,10]; // 半音位置
const WHITE_KEY_MAP = { 'a': 0, 's': 1, 'd': 2, 'f': 3, 'g': 4, 'h': 5, 'j': 6, 'k': 7, 'l': 8 };
const BLACK_KEY_MAP = { 'w': 0, 'e': 1, 't': 3, 'y': 4, 'u': 5, 'o': 6, 'p': 7 };
const KEY_MAP = {};
Object.entries(WHITE_KEY_MAP).forEach(([k, v]) => KEY_MAP[k] = { type: 'white', index: v });
Object.entries(BLACK_KEY_MAP).forEach(([k, v]) => KEY_MAP[k] = { type: 'black', index: v });
function freqForNote(noteIndex, octave) {
const semitone = noteIndex + (octave - 4) * 12;
return 440 * Math.pow(2, (semitone - 9) / 12);
}
function buildKeyboard() {
const container = document.getElementById('keysContainer');
container.innerHTML = '';
// 2个八度: C3-B4
const startOctave = 3;
const numOctaves = 2;
for (let oct = startOctave; oct < startOctave + numOctaves; oct++) {
for (let n = 0; n < 12; n++) {
const isBlack = BLACK_INDICES.includes(n);
const freq = freqForNote(n, oct);
if (!isBlack) {
const wrapper = document.createElement('div');
wrapper.className = 'key-wrapper';
const key = document.createElement('div');
key.className = 'white-key';
key.dataset.note = n;
key.dataset.octave = oct;
key.dataset.freq = freq;
// 键盘标签
const whiteIdx = n - Math.floor(n / 5) * 1; // 简化映射
const keyLabels = ['A','S','D','F','G','H','J','K','L'];
const labelIdx = (oct - startOctave) * 7 + (n % 7);
const keyLabel = document.createElement('div');
keyLabel.className = 'key-label';
keyLabel.textContent = keyLabels[labelIdx % keyLabels.length];
const noteLabel = document.createElement('div');
noteLabel.className = 'note-label';
noteLabel.textContent = NOTE_NAMES[n] + oct;
const glow = document.createElement('div');
glow.className = 'key-glow';
key.appendChild(keyLabel);
key.appendChild(noteLabel);
key.appendChild(glow);
key.addEventListener('mousedown', (e) => {
e.preventDefault();
key.classList.add('pressed');
playPianoNote(freq);
updateVisualizer();
});
key.addEventListener('mouseup', () => key.classList.remove('pressed'));
key.addEventListener('mouseleave', () => key.classList.remove('pressed'));
key.addEventListener('touchstart', (e) => {
e.preventDefault();
key.classList.add('pressed');
playPianoNote(freq);
updateVisualizer();
});
key.addEventListener('touchend', () => key.classList.remove('pressed'));
wrapper.appendChild(key);
container.appendChild(wrapper);
}
}
}
// 放置黑键 (绝对定位)
const whiteKeys = container.querySelectorAll('.white-key');
let whiteIdx = 0;
for (let oct = startOctave; oct < startOctave + numOctaves; oct++) {
for (let n = 0; n < 12; n++) {
if (BLACK_INDICES.includes(n)) {
const freq = freqForNote(n, oct);
// 找到对应的白键位置
let targetWhite = whiteIdx + Math.floor((BLACK_INDICES.indexOf(n)) * 0.6);
if (targetWhite >= whiteKeys.length) targetWhite = whiteKeys.length - 1;
const wrapper = document.createElement('div');
wrapper.className = 'key-wrapper';
wrapper.style.position = 'absolute';
wrapper.style.zIndex = '2';
const key = document.createElement('div');
key.className = 'black-key';
key.dataset.note = n;
key.dataset.octave = oct;
key.dataset.freq = freq;
const noteLabel = document.createElement('div');
noteLabel.className = 'note-label';
noteLabel.textContent = NOTE_NAMES[n] + oct;
const glow = document.createElement('div');
glow.className = 'key-glow';
key.appendChild(noteLabel);
key.appendChild(glow);
// 定位到白键之间
const whiteWidth = 100 / (numOctaves * 7 + (numOctaves - 1));
key.style.width = whiteWidth * 0.65 + '%';
key.style.left = (whiteIdx + 0.5 - (BLACK_INDICES.indexOf(n) < 2 ? 0 : 0.1)) * whiteWidth + '%';
key.addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
key.classList.add('pressed');
playPianoNote(freq);
updateVisualizer();
});
key.addEventListener('mouseup', () => key.classList.remove('pressed'));
key.addEventListener('mouseleave', () => key.classList.remove('pressed'));
key.addEventListener('touchstart', (e) => {
e.preventDefault();
key.classList.add('pressed');
playPianoNote(freq);
updateVisualizer();
});
key.addEventListener('touchend', () => key.classList.remove('pressed'));
wrapper.appendChild(key);
container.appendChild(wrapper);
}
if (!BLACK_INDICES.includes(n)) {
// 只在白键处增加计数
// 实际whiteIdx已经在循环外管理
}
}
whiteIdx += 7;
}
// 重新精确定位黑键
positionBlackKeys(container, startOctave, numOctaves);
}
function positionBlackKeys(container, startOctave, numOctaves) {
const allKeys = container.querySelectorAll('.key-wrapper');
const whiteWrappers = [];
const blackWrappers = [];
allKeys.forEach(w => {
if (w.querySelector('.white-key')) whiteWrappers.push(w);
else if (w.querySelector('.black-key')) blackWrappers.push(w);
});
// 移除错误定位的黑键
blackWrappers.forEach(bw => bw.remove());
let whiteIdx = 0;
for (let oct = startOctave; oct < startOctave + numOctaves; oct++) {
for (let n = 0; n < 12; n++) {
if (BLACK_INDICES.includes(n)) {
const freq = freqForNote(n, oct);
const noteName = NOTE_NAMES[n] + oct;
const wrapper = document.createElement('div');
wrapper.className = 'key-wrapper';
wrapper.style.position = 'absolute';
wrapper.style.zIndex = '2';
wrapper.style.left = '0';
wrapper.style.bottom = '0';
wrapper.style.top = '0';
const key = document.createElement('div');
key.className = 'black-key';
key.dataset.note = n;
key.dataset.octave = oct;
key.dataset.freq = freq;
const noteLabel = document.createElement('div');
noteLabel.className = 'note-label';
noteLabel.textContent = noteName;
const glow = document.createElement('div');
glow.className = 'key-glow';
key.appendChild(noteLabel);
key.appendChild(glow);
key.addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
key.classList.add('pressed');
playPianoNote(freq);
updateVisualizer();
});
key.addEventListener('mouseup', () => key.classList.remove('pressed'));
key.addEventListener('mouseleave', () => key.classList.remove('pressed'));
key.addEventListener('touchstart', (e) => {
e.preventDefault();
key.classList.add('pressed');
playPianoNote(freq);
updateVisualizer();
});
key.addEventListener('touchend', () => key.classList.remove('pressed'));
wrapper.appendChild(key);
container.appendChild(wrapper);
}
if (!BLACK_INDICES.includes(n)) {
// 白键计数在上面的循环已经处理
}
}
}
// 用JS计算精确位置
const totalWhites = numOctaves * 7;
const whiteWidthPercent = 100 / totalWhites;
blackWrappers.length = 0;
container.querySelectorAll('.black-key').forEach(bk => {
blackWrappers.push(bk.parentElement);
});
blackWrappers.forEach(bw => bw.remove());
let bIdx = 0;
for (let oct = startOctave; oct < startOctave + numOctaves; oct++) {
let wCount = 0;
for (let n = 0; n < 12; n++) {
if (BLACK_INDICES.includes(n)) {
const freq = freqForNote(n, oct);
const wrapper = document.createElement('div');
wrapper.className = 'key-wrapper';
wrapper.style.position = 'absolute';
wrapper.style.zIndex = '2';
wrapper.style.left = '0';
wrapper.style.bottom = '0';
wrapper.style.top = '0';
const key = document.createElement('div');
key.className = 'black-key';
key.dataset.note = n;
key.dataset.octave = oct;
key.dataset.freq = freq;
// 精确定位: 黑键在相邻白键之间
const blackPositions = [0.65, 1.75, 3.65, 4.75, 5.85]; // 在每个八度内黑键相对于白键起点
const octOffset = (oct - startOctave) * 7;
const posInOct = BLACK_INDICES.indexOf(n);
const xPos = (octOffset + blackPositions[posInOct]) * whiteWidthPercent;
key.style.left = xPos + '%';
key.style.width = (whiteWidthPercent * 0.6) + '%';
const noteLabel = document.createElement('div');
noteLabel.className = 'note-label';
noteLabel.textContent = NOTE_NAMES[n] + oct;
const glow = document.createElement('div');
glow.className = 'key-glow调用失败:fetch failed
调用失败:HTTP 403: {"error":{"message":"Free quota exhausted. To continue accessing the model on a paid basis, please add funds or disable the \"use free tier only\" mode in the management console.","type":"AllocationQu
调用异常
- 豆包:fetch failed
- 通义千问:HTTP 403: {"error":{"message":"Free quota exhausted. To continue accessing the model on a paid basis, please add funds or disable the \"use free tier only\" mode in the management console.","type":"AllocationQu
评分结论
按「质量 70% + 性能 30%」加权,本场横评综合表现最佳:DeepSeek(综合分 7.8)。
质量分为测评人按正确性/可运行性 / 逻辑性 / 完整性 / 稳定性 / 风格 / 效率六维人工打分加权得出。
方法与复现
- 实测主体
- 爱点评编辑团队
- 实测日期
- 2026-10-16
- 模型版本
- 豆包、百度文心、DeepSeek、智谱 GLM、通义千问、Kimi
- 复现包
- 整理中
常见问题
- 《同题横评:做一个网页版的电子琴,声音逼真,外观也仿真立体》对比了哪些 AI 产品?
- 本次横评共覆盖 4 款产品:智谱清言、Kimi、DeepSeek 对话、通义千问。所有产品在同一题目、相同环境下实测。
- 《同题横评:做一个网页版的电子琴,声音逼真,外观也仿真立体》的核心结论是什么?
- > 本报告由「AI 大众点评 · 同题横评工作台」自动生成,同一任务并发调用多家大模型后对比输出。
- 这份横评报告是如何产生的?
- AI 大众点评 的横评报告基于同一题目、同一任务,由真人完整操作各 AI 产品并记录全过程,评分覆盖正确性、逻辑性、完整性、稳定性、风格与效率等维度,翻车情况也会如实呈现。
评论(0)
评论加载中…


