js实现launchpad
实现 Launchpad 的基本思路
Launchpad 是一种类似音乐制作软件的网格界面,允许用户触发音频样本或 MIDI 音符。以下是通过 JavaScript 实现的基本方法。
HTML 结构
创建一个简单的网格布局,使用 <div> 元素表示每个 pad:
<div id="launchpad">
<div class="pad" data-note="C4"></div>
<div class="pad" data-note="D4"></div>
<!-- 更多 pad -->
</div>
CSS 样式
为 Launchpad 和每个 pad 添加基本样式:

#launchpad {
display: grid;
grid-template-columns: repeat(8, 1fr);
gap: 5px;
width: 400px;
height: 400px;
}
.pad {
background-color: #333;
border-radius: 5px;
cursor: pointer;
}
.pad.active {
background-color: #ff0;
}
JavaScript 功能
使用 Web Audio API 处理音频:
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
document.querySelectorAll('.pad').forEach(pad => {
pad.addEventListener('mousedown', () => {
playNote(pad.dataset.note);
pad.classList.add('active');
});
pad.addEventListener('mouseup', () => {
pad.classList.remove('active');
});
});
function playNote(note) {
const oscillator = audioContext.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = getFrequency(note);
oscillator.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.5);
}
function getFrequency(note) {
// 返回对应音符的频率
const notes = {
'C4': 261.63,
'D4': 293.66,
'E4': 329.63,
'F4': 349.23,
'G4': 392.00,
'A4': 440.00,
'B4': 493.88
};
return notes[note] || 440;
}
添加键盘控制
扩展功能以支持键盘控制:

document.addEventListener('keydown', (e) => {
const keyNoteMap = {
'a': 'C4',
's': 'D4',
'd': 'E4',
'f': 'F4',
'g': 'G4',
'h': 'A4',
'j': 'B4'
};
if (keyNoteMap[e.key]) {
playNote(keyNoteMap[e.key]);
const pad = document.querySelector(`[data-note="${keyNoteMap[e.key]}"]`);
pad.classList.add('active');
}
});
document.addEventListener('keyup', (e) => {
const keyNoteMap = {
'a': 'C4',
's': 'D4',
'd': 'E4',
'f': 'F4',
'g': 'G4',
'h': 'A4',
'j': 'B4'
};
if (keyNoteMap[e.key]) {
const pad = document.querySelector(`[data-note="${keyNoteMap[e.key]}"]`);
pad.classList.remove('active');
}
});
使用预录样本
替换简单的振荡器为预录音频样本:
function playSample(url) {
fetch(url)
.then(response => response.arrayBuffer())
.then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start();
});
}
// 修改 playNote 函数
function playNote(note) {
const sampleMap = {
'C4': 'samples/kick.wav',
'D4': 'samples/snare.wav'
// 其他样本
};
playSample(sampleMap[note]);
}
实现序列器功能
添加简单的步进序列器:
let sequence = [true, false, true, false]; // 示例序列
let currentStep = 0;
function playSequence() {
if (sequence[currentStep]) {
const pads = document.querySelectorAll('.pad');
playNote(pads[currentStep % pads.length].dataset.note);
}
currentStep = (currentStep + 1) % sequence.length;
}
setInterval(playSequence, 500); // 每500ms前进一步
这些代码片段展示了如何实现一个基本的 JavaScript Launchpad。可以根据需要扩展功能,如添加更多音色、效果或更复杂的序列器逻辑。






