react实现手工琴
React 实现手工琴
要实现一个手工琴(如虚拟钢琴或简单乐器)的 React 应用,可以结合 HTML5 的 Web Audio API 或第三方音频库(如 Tone.js)来生成声音,并通过 React 的交互逻辑控制按键。以下是具体实现方法:
使用 Web Audio API 实现基础音效
创建一个音频上下文,并通过振荡器(Oscillator)生成不同频率的声音。以下是一个简单的音调生成函数:
function playNote(frequency, duration = 0.5) {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.type = 'sine'; // 波形:sine(正弦波)、square(方波)等
oscillator.frequency.value = frequency;
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.start();
gainNode.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + duration);
oscillator.stop(audioCtx.currentTime + duration);
}
创建琴键组件
为每个琴键创建一个 React 组件,绑定点击或键盘事件触发音效。例如:

const Key = ({ note, frequency, color }) => {
const handleClick = () => playNote(frequency);
return (
<button
style={{
width: '60px',
height: '200px',
backgroundColor: color,
border: '1px solid #000',
}}
onClick={handleClick}
>
{note}
</button>
);
};
构建完整键盘
定义音符和频率的映射关系,渲染一组琴键:
const notes = [
{ note: 'C4', frequency: 261.63, color: 'white' },
{ note: 'D4', frequency: 293.66, color: 'white' },
{ note: 'E4', frequency: 329.63, color: 'white' },
{ note: 'F4', frequency: 349.23, color: 'white' },
{ note: 'G4', frequency: 392.00, color: 'white' },
{ note: 'A4', frequency: 440.00, color: 'white' },
{ note: 'B4', frequency: 493.88, color: 'white' },
];
const Piano = () => {
return (
<div style={{ display: 'flex' }}>
{notes.map(({ note, frequency, color }) => (
<Key key={note} note={note} frequency={frequency} color={color} />
))}
</div>
);
};
扩展功能
-
键盘事件支持
监听keydown事件,将物理键盘按键映射到琴键:
useEffect(() => { const handleKeyPress = (e) => { const keyMap = { 'a': 'C4', 's': 'D4', 'd': 'E4' }; // 自定义映射 const note = keyMap[e.key]; if (note) playNote(notes.find(n => n.note === note).frequency); }; window.addEventListener('keydown', handleKeyPress); return () => window.removeEventListener('keydown', handleKeyPress); }, []); -
使用 Tone.js 增强音效
安装 Tone.js 库(npm install tone),提供更丰富的音色和效果:import * as Tone from 'tone'; const playNote = (note) => { const synth = new Tone.Synth().toDestination(); synth.triggerAttackRelease(note, '8n'); }; -
样式优化
使用 CSS 或库(如 styled-components)美化琴键,例如为黑键添加特殊样式:const BlackKey = styled(Key)` background-color: black; height: 120px; margin-left: -15px; margin-right: -15px; z-index: 1; `;
完整示例代码
import React, { useEffect } from 'react';
import styled from 'styled-components';
const Key = ({ note, frequency, color }) => {
const handleClick = () => playNote(frequency);
return (
<button
style={{
width: '60px',
height: color === 'black' ? '120px' : '200px',
backgroundColor: color,
border: '1px solid #000',
position: color === 'black' ? 'absolute' : 'relative',
}}
onClick={handleClick}
>
{note}
</button>
);
};
const Piano = () => {
const notes = [
{ note: 'C4', frequency: 261.63, color: 'white' },
{ note: 'C#4', frequency: 277.18, color: 'black' },
{ note: 'D4', frequency: 293.66, color: 'white' },
// 更多音符...
];
return (
<div style={{ display: 'flex', position: 'relative' }}>
{notes.map(({ note, frequency, color }) => (
<Key key={note} note={note} frequency={frequency} color={color} />
))}
</div>
);
};
export default Piano;
通过以上步骤,可以快速实现一个基础的 React 手工琴应用,并进一步扩展音色、交互或动画效果。






