js实现launchpad
以下是使用JavaScript实现简易Launchpad(音乐网格)的几种方法,涵盖基础功能与交互逻辑:
基础HTML/CSS结构
创建网格布局并定义样式:
<div class="launchpad-container">
<div class="pad-row" v-for="(row, rowIndex) in pads" :key="rowIndex">
<div
class="pad"
v-for="(pad, colIndex) in row"
:key="colIndex"
@mousedown="playSound(rowIndex, colIndex)"
@touchstart="playSound(rowIndex, colIndex)"
></div>
</div>
</div>
.launchpad-container {
display: grid;
grid-template-columns: repeat(4, 80px);
gap: 10px;
padding: 20px;
}
.pad {
width: 80px;
height: 80px;
background: #333;
border-radius: 8px;
cursor: pointer;
transition: all 0.1s;
}
.pad.active {
transform: scale(0.95);
background: #666;
}
音频处理核心逻辑
使用Web Audio API加载和播放音频:
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const pads = [
['kick.mp3', 'snare.mp3', 'hihat.mp3', 'clap.mp3'],
// ...其他行音频配置
];
const buffers = {};
function loadAudio() {
pads.flat().forEach(sample => {
fetch(`sounds/${sample}`)
.then(response => response.arrayBuffer())
.then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
buffers[sample] = audioBuffer;
});
});
}
function playSound(row, col) {
const sampleName = pads[row][col];
const source = audioContext.createBufferSource();
source.buffer = buffers[sampleName];
source.connect(audioContext.destination);
source.start();
}
交互增强功能
添加视觉反馈和移动端支持:
document.querySelectorAll('.pad').forEach(pad => {
pad.addEventListener('mousedown', function() {
this.classList.add('active');
});
pad.addEventListener('mouseup', function() {
this.classList.remove('active');
});
pad.addEventListener('mouseleave', function() {
this.classList.remove('active');
});
});
// 移动端touch事件处理
document.addEventListener('touchmove', function(e) {
e.preventDefault();
}, { passive: false });
进阶功能扩展
实现录音和序列播放:
let isRecording = false;
let recordedSteps = [];
function toggleRecording() {
isRecording = !isRecording;
if (isRecording) recordedSteps = [];
}
function playSequence(bpm = 120) {
const interval = 60000 / bpm / 4; // 16分音符间隔
recordedSteps.forEach((step, i) => {
setTimeout(() => {
playSound(step.row, step.col);
}, i * interval);
});
}
性能优化建议
- 预加载所有音频文件避免延迟
- 使用共享AudioContext实例
- 对移动端设备减少同时发声数
- 实现Web Workers处理复杂音频处理
完整实现需要根据具体需求调整网格尺寸、音频样本和交互细节。现代前端框架如React/Vue可帮助管理状态和组件化开发。







