基础概念: JavaScript 制作钢琴是通过在网页上模拟钢琴键盘的外观和功能,使用 JavaScript 监听键盘事件,从而触发相应的音频播放。
优势:
类型:
应用场景:
常见问题及解决方法:
requestAnimationFrame
优化动画效果。示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript 钢琴</title>
<style>
.piano-key {
width: 50px;
height: 200px;
background-color: white;
border: 1px solid black;
display: inline-block;
margin-right: 2px;
}
.black-key {
width: 30px;
height: 120px;
background-color: black;
position: relative;
top: -120px;
left: 10px;
}
</style>
</head>
<body>
<div id="piano">
<!-- 白键 -->
<div class="piano-key" data-note="C4"></div>
<div class="piano-key black-key" data-note="C#4"></div>
<div class="piano-key" data-note="D4"></div>
<!-- 更多键... -->
</div>
<script>
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const keys = document.querySelectorAll('.piano-key');
keys.forEach(key => {
key.addEventListener('mousedown', () => playNote(key.dataset.note));
key.addEventListener('mouseup', () => stopNote());
});
function playNote(note) {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.value = getFrequency(note);
gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
oscillator.start();
oscillator.stop(audioContext.currentTime + 1);
}
function stopNote() {
// 停止播放逻辑
}
function getFrequency(note) {
// 根据音符返回频率
}
</script>
</body>
</html>
在这个示例中,我们创建了一个简单的钢琴界面,并使用 JavaScript 监听键盘事件来播放相应的音符。你可以根据需要扩展和优化这个示例。
领取专属 10元无门槛券
手把手带您无忧上云