当前位置:首页 > React

react实现手工琴

2026-01-26 18:59:02React

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>
  );
};

扩展功能

  1. 键盘事件支持
    监听 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);
    }, []);
  2. 使用 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');
    };
  3. 样式优化
    使用 CSS 或库(如 styled-components)美化琴键,例如为黑键添加特殊样式:

    react实现手工琴

    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 手工琴应用,并进一步扩展音色、交互或动画效果。

标签: 手工react
分享给朋友:

相关文章

react如何鉴定

react如何鉴定

React 鉴权方法 基于路由的鉴权 在 React 中,可以通过封装路由组件实现鉴权。使用 react-router-dom 检查用户是否登录,未登录则跳转至登录页。 import { Rou…

如何开发react

如何开发react

开发React应用的基本步骤 安装Node.js和npm 确保系统中已安装Node.js(包含npm)。可通过官网下载安装包,安装后验证版本: node -v npm -v 创建React项目…

react如何重启

react如何重启

重启 React 应用的方法 重新加载当前页面 使用 window.location.reload() 强制刷新页面,这会重新加载整个应用并重置所有状态。 window.location…

react native如何

react native如何

React Native 基础知识 React Native 是一个由 Facebook 开发的框架,用于使用 JavaScript 和 React 构建跨平台移动应用。它允许开发者编写一次代码,同时…

如何监控react性能

如何监控react性能

使用 React Profiler API React 16.5 及以上版本内置了 Profiler API,可直接测量组件渲染时间。通过 <React.Profiler> 包裹目标组件,…

如何运行react项目

如何运行react项目

运行React项目的步骤 确保已安装Node.js(建议版本12或更高)和npm/yarn。若未安装,可从Node.js官网下载。 全局安装create-react-app脚手架工具(若已安装可跳过…