vue实现电子琴
Vue 实现电子琴的基本思路
使用 Vue 实现电子琴需要结合 HTML5 的 Web Audio API 或第三方音频库(如 Tone.js)来生成声音,并通过 Vue 的响应式特性管理交互状态。以下是具体实现方法:
安装依赖(可选)
若使用 Tone.js 简化音频处理,需先安装:
npm install tone
核心代码实现
1. 创建音频上下文或初始化 Tone.js
使用 Web Audio API:
// 在 Vue 的 methods 或 setup 中
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillators = {}; // 存储当前活跃的振荡器
或使用 Tone.js:
import * as Tone from 'tone';
// 初始化合成器
const synth = new Tone.Synth().toDestination();
2. 定义琴键数据
在 Vue 的 data 或 setup 中定义音高序列:
const notes = ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4']; // 示例音高
3. 渲染琴键界面
通过 v-for 动态生成琴键:
<template>
<div class="piano">
<div
v-for="(note, index) in notes"
:key="index"
class="key"
@mousedown="playNote(note)"
@mouseup="stopNote(note)"
@mouseleave="stopNote(note)"
>
{{ note }}
</div>
</div>
</template>
4. 实现播放/停止逻辑
Web Audio API 版本:
methods: {
playNote(note) {
const osc = audioContext.createOscillator();
osc.frequency.value = this.getFrequency(note); // 需实现音高转频率
osc.connect(audioContext.destination);
osc.start();
this.oscillators[note] = osc;
},
stopNote(note) {
if (this.oscillators[note]) {
this.oscillators[note].stop();
delete this.oscillators[note];
}
}
}
Tone.js 版本:
methods: {
playNote(note) {
synth.triggerAttack(note);
},
stopNote(note) {
synth.triggerRelease();
}
}
5. 添加样式
通过 CSS 美化琴键:
.piano {
display: flex;
}
.key {
width: 60px;
height: 200px;
border: 1px solid #000;
background: white;
cursor: pointer;
}
.key:active {
background: #ddd;
}
扩展功能
- 键盘映射:监听
keydown事件,将物理键盘按键映射到琴键。 - 音色切换:通过 Web Audio API 的
Oscillator.type或 Tone.js 的synth.oscillator.type修改波形(sine/square/sawtooth)。 - 效果器:添加混响、延迟等效果(Tone.js 提供内置效果链)。
完整示例(Vue 3 + Tone.js)
<template>
<div class="piano">
<div
v-for="(note, index) in notes"
:key="index"
class="key"
@mousedown="playNote(note)"
@mouseup="stopNote"
@mouseleave="stopNote"
>
{{ note }}
</div>
</div>
</template>
<script>
import { onMounted } from 'vue';
import * as Tone from 'tone';
export default {
setup() {
const notes = ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4'];
const synth = new Tone.Synth().toDestination();
const playNote = (note) => {
synth.triggerAttack(note);
};
const stopNote = () => {
synth.triggerRelease();
};
onMounted(() => {
// 首次交互时唤醒音频上下文(浏览器策略要求)
document.addEventListener('click', async () => {
await Tone.start();
});
});
return { notes, playNote, stopNote };
}
};
</script>
通过以上步骤,即可实现一个基础的 Vue 电子琴应用。根据需求可进一步扩展音阶范围、UI 交互或音频效果。







