feat: Web Audio 复音合成器(16 音色族 + 鼓组 + 混响 + 偷声)

This commit is contained in:
2026-09-24 03:38:43 +00:00
parent 18061c3d93
commit 2f52386a77
+462
View File
@@ -0,0 +1,462 @@
/*
* synth.js —— 基于 Web Audio API 的多音色复音合成器
* ------------------------------------------------------------------
* 设计要点:
* 1. 每个音符 = 一个 Voice 对象:多个振荡器 -> 低通滤波 -> ADSR 包络 -> 输出
* 2. 音色按 General MIDI 的 16 个乐器族(program / 8)归类,用一个参数表描述
* 3. 通道 9(第 10 通道)特殊处理为鼓组,用噪声 + 音高包络合成打击乐
* 4. 支持 CC7(音量) / CC10(声像) / CC11(表情) / CC120,123(全部音符关闭)
* 5. 支持复音数上限与"偷声"(voice stealing),避免卡顿
* 6. 生成式脉冲响应卷积混响,无需外部音频资源
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.MidiSynth = factory();
})(typeof self !== 'undefined' ? self : this, function () {
'use strict';
/* ---------------------------------------------------------------- */
/* 音色参数表:w=[相对音量, 波形, 八度偏移, 失谐(音分)] */
/* a 起音 / d 衰减 / s 保持 / r 释放 (秒) */
/* cut 低通截止 / q 品质因数 / rev 混响发送量 / gain 总增益 */
/* ---------------------------------------------------------------- */
var FAMILIES = [
/* 0 钢琴 */ { w: [[0.85, 'triangle'], [0.45, 'sine', 1], [0.12, 'sawtooth']], a: 0.004, d: 1.6, s: 0.16, r: 0.35, cut: 3200, q: 0.7, rev: 0.16, gain: 1.0 },
/* 1 半音打击 */ { w: [[0.9, 'sine'], [0.35, 'triangle', 1]], a: 0.003, d: 0.9, s: 0.05, r: 0.5, cut: 4200, q: 0.7, rev: 0.30, gain: 0.95 },
/* 2 风琴 */ { w: [[0.7, 'square'], [0.5, 'square', 1], [0.32, 'sine', -1]], a: 0.012, d: 0.05, s: 0.95, r: 0.12, cut: 2600, q: 0.5, rev: 0.20, gain: 0.75 },
/* 3 吉他 */ { w: [[0.8, 'sawtooth'], [0.4, 'triangle', 1]], a: 0.006, d: 0.9, s: 0.12, r: 0.35, cut: 2800, q: 0.8, rev: 0.18, gain: 0.95 },
/* 4 贝斯 */ { w: [[0.9, 'sawtooth'], [0.6, 'sine', -1]], a: 0.008, d: 0.6, s: 0.45, r: 0.18, cut: 1100, q: 1.0, rev: 0.05, gain: 1.15 },
/* 5 弦乐 */ { w: [[0.8, 'sawtooth'], [0.8, 'sawtooth', 0, 7]], a: 0.18, d: 0.4, s: 0.85, r: 0.7, cut: 2400, q: 0.6, rev: 0.45, gain: 0.8 },
/* 6 合奏 */ { w: [[0.7, 'sawtooth'], [0.6, 'square', 0, -6]], a: 0.12, d: 0.4, s: 0.85, r: 0.6, cut: 2200, q: 0.6, rev: 0.42, gain: 0.8 },
/* 7 铜管 */ { w: [[0.9, 'sawtooth'], [0.4, 'square', 1]], a: 0.06, d: 0.3, s: 0.78, r: 0.3, cut: 3000, q: 0.9, rev: 0.28, gain: 0.85 },
/* 8 簧管 */ { w: [[0.8, 'square'], [0.4, 'sawtooth', 0, 5]], a: 0.05, d: 0.3, s: 0.82, r: 0.3, cut: 2000, q: 0.8, rev: 0.30, gain: 0.75 },
/* 9 吹管 */ { w: [[0.9, 'sine'], [0.35, 'triangle', 1], [0.08, 'sawtooth']], a: 0.08, d: 0.3, s: 0.88, r: 0.35, cut: 3400, q: 0.6, rev: 0.40, gain: 0.85 },
/* 10 合成主音 */ { w: [[0.9, 'sawtooth'], [0.5, 'square', 0, 8]], a: 0.02, d: 0.35, s: 0.6, r: 0.3, cut: 2800, q: 1.2, rev: 0.25, gain: 0.8 },
/* 11 合成铺底 */ { w: [[0.7, 'sawtooth'], [0.7, 'triangle', 0, -9], [0.4, 'sine', 1]], a: 0.6, d: 1.2, s: 0.7, r: 1.4, cut: 1600, q: 0.5, rev: 0.60, gain: 0.7 },
/* 12 音效 */ { w: [[0.6, 'sawtooth'], [0.5, 'sine', 1]], a: 0.4, d: 1.5, s: 0.5, r: 1.4, cut: 1800, q: 0.7, rev: 0.60, gain: 0.7 },
/* 13 民族 */ { w: [[0.8, 'triangle'], [0.4, 'sawtooth', 1]], a: 0.01, d: 0.8, s: 0.2, r: 0.4, cut: 2800, q: 0.8, rev: 0.25, gain: 0.9 },
/* 14 打击 */ { w: [[0.8, 'triangle'], [0.4, 'square', 1]], a: 0.002, d: 0.5, s: 0.03, r: 0.3, cut: 4500, q: 0.7, rev: 0.30, gain: 0.9 },
/* 15 特效 */ { w: [[0.7, 'sawtooth'], [0.5, 'square', 1]], a: 0.05, d: 1.2, s: 0.2, r: 0.8, cut: 2200, q: 0.7, rev: 0.50, gain: 0.7 }
];
function familyFor(program, channel) {
if (channel === 9) return FAMILIES[14];
var p = program | 0;
if (p < 0) p = 0; else if (p > 127) p = 127;
return FAMILIES[Math.min(15, Math.floor(p / 8))];
}
/* ------------------------- 鼓组音色映射 ------------------------- */
function drumSpec(midi) {
switch (midi) {
case 35: case 36: return { kind: 'kick', f0: 165, f1: 45, decay: 0.38, gain: 1.0, rev: 0.05 };
case 38: case 40: return { kind: 'snare', decay: 0.24, gain: 0.55, freq: 1800, q: 0.9, body: 190, bf1: 130, bg: 0.45, rev: 0.22 };
case 37: return { kind: 'clap', decay: 0.12, gain: 0.4, freq: 2400, q: 1.4, rev: 0.2 };
case 39: return { kind: 'clap', decay: 0.22, gain: 0.5, freq: 1400, q: 1.2, rev: 0.25 };
case 42: return { kind: 'hat', decay: 0.06, gain: 0.32, freq: 9500, q: 0.8, rev: 0.06 };
case 44: return { kind: 'hat', decay: 0.09, gain: 0.32, freq: 7500, q: 0.8, rev: 0.08 };
case 46: return { kind: 'hat', decay: 0.38, gain: 0.30, freq: 8200, q: 0.7, rev: 0.18 };
case 49: return { kind: 'cymbal', decay: 1.5, gain: 0.30, freq: 6200, q: 0.5, rev: 0.4 };
case 57: return { kind: 'cymbal', decay: 1.0, gain: 0.30, freq: 7200, q: 0.5, rev: 0.35 };
case 51: case 59: return { kind: 'cymbal', decay: 0.7, gain: 0.26, freq: 8200, q: 0.6, rev: 0.25 };
case 41: case 43: return { kind: 'tom', f0: 130, f1: 80, decay: 0.38, gain: 0.7, rev: 0.2 };
case 45: case 47: return { kind: 'tom', f0: 180, f1: 110, decay: 0.34, gain: 0.7, rev: 0.2 };
case 48: case 50: return { kind: 'tom', f0: 235, f1: 145, decay: 0.3, gain: 0.7, rev: 0.2 };
default: return { kind: 'noise', decay: 0.16, gain: 0.4, freq: 1600, q: 0.9, rev: 0.2 };
}
}
/* --------------------------- 工具函数 --------------------------- */
function makeNoiseBuffer(ctx, seconds) {
var len = Math.floor(ctx.sampleRate * seconds);
var buf = ctx.createBuffer(1, len, ctx.sampleRate);
var d = buf.getChannelData(0);
for (var i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;
return buf;
}
/* 生成一段指数衰减的噪声作为混响脉冲响应 */
function makeImpulse(ctx, seconds, decay) {
var len = Math.floor(ctx.sampleRate * seconds);
var buf = ctx.createBuffer(2, len, ctx.sampleRate);
for (var c = 0; c < 2; c++) {
var d = buf.getChannelData(c);
for (var i = 0; i < len; i++) {
d[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, decay);
}
}
return buf;
}
function clampTime(ctx, t) {
var now = ctx.currentTime;
return (t == null || t < now) ? now : t;
}
/* 冻结某个 AudioParam 在时刻 t 的值(优先使用 cancelAndHoldAtTime) */
function holdParam(param, t) {
if (typeof param.cancelAndHoldAtTime === 'function') {
try { param.cancelAndHoldAtTime(t); return; } catch (e) { /* 继续走降级方案 */ }
}
var v = param.value;
param.cancelScheduledValues(t);
param.setValueAtTime(v, t);
}
/* ============================ 旋律声部 ============================ */
function Voice(synth, channel, midi, velocity, when, program) {
this.synth = synth;
this.ctx = synth.ctx;
this.channel = channel;
this.midi = midi;
this.key = channel * 128 + midi;
this.released = false;
this.stopTime = Infinity;
this.isDrum = false;
var ctx = this.ctx;
var fam = familyFor(program, channel);
this.fam = fam;
var freq = 440 * Math.pow(2, (midi - 69) / 12);
this.freq = freq;
var vel = Math.max(1, Math.min(127, velocity)) / 127;
var peak = Math.pow(vel, 1.35) * 0.30 * fam.gain;
this.peak = peak;
var t0 = when;
var out = ctx.createGain();
out.gain.setValueAtTime(0.0001, t0);
out.gain.linearRampToValueAtTime(peak, t0 + fam.a);
out.gain.linearRampToValueAtTime(Math.max(peak * fam.s, 0.0001), t0 + fam.a + fam.d);
var filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
var nyq = ctx.sampleRate / 2;
var cut = fam.cut * (0.55 + 0.45 * vel) + freq * 0.8;
cut = Math.max(180, Math.min(cut, nyq - 800));
filter.frequency.setValueAtTime(cut, t0);
filter.frequency.exponentialRampToValueAtTime(Math.max(180, cut * 0.45), t0 + fam.a + fam.d + 0.05);
filter.Q.value = fam.q;
filter.connect(out);
/* 振荡器组 */
this.oscs = [];
for (var i = 0; i < fam.w.length; i++) {
var spec = fam.w[i];
var f = freq * Math.pow(2, spec[2] || 0);
if (f > nyq - 500) continue;
var osc = ctx.createOscillator();
osc.type = spec[1];
osc.frequency.setValueAtTime(f, t0);
if (spec[3]) osc.detune.setValueAtTime(spec[3], t0);
var og = ctx.createGain();
og.gain.value = spec[0];
osc.connect(og);
og.connect(filter);
osc.start(t0);
this.oscs.push(osc);
}
/* 输出路由:干声进通道总线,湿声送混响总线 */
out.connect(synth.channels[channel].vol);
if (synth.reverb && fam.rev > 0.01) {
var send = ctx.createGain();
send.gain.value = fam.rev;
out.connect(send);
send.connect(synth.reverb);
this.send = send;
}
this.out = out;
this.filter = filter;
}
Voice.prototype.release = function (when) {
if (this.released) return;
this.released = true;
var ctx = this.ctx;
var t = clampTime(ctx, when);
var rel = this.fam.r;
holdParam(this.out.gain, t);
this.out.gain.linearRampToValueAtTime(0.0001, t + rel);
this.stopTime = t + rel + 0.06;
this._stopOscs(this.stopTime);
};
/* 立即掐断(用于偷声 / 全部音符关闭) */
Voice.prototype.cut = function (when) {
this.released = true;
var t = clampTime(this.ctx, when);
holdParam(this.out.gain, t);
this.out.gain.linearRampToValueAtTime(0.0001, t + 0.025);
this.stopTime = t + 0.05;
this._stopOscs(this.stopTime);
};
Voice.prototype._stopOscs = function (t) {
for (var i = 0; i < this.oscs.length; i++) {
try { this.oscs[i].stop(t); } catch (e) { /* 已停止 */ }
}
};
/* ============================ 鼓组声部 ============================ */
function DrumVoice(synth, midi, velocity, when) {
this.synth = synth;
this.ctx = synth.ctx;
this.midi = midi;
this.key = 9 * 128 + midi;
this.channel = 9;
this.released = true; // 打击乐不需要 note-off
this.isDrum = true;
var ctx = this.ctx;
var spec = drumSpec(midi);
var vel = Math.max(1, Math.min(127, velocity)) / 127;
var amp = Math.pow(vel, 1.2) * spec.gain;
var dur = spec.decay;
var t0 = when;
var out = ctx.createGain();
out.gain.setValueAtTime(Math.max(amp, 0.0001), t0);
out.gain.exponentialRampToValueAtTime(0.0005, t0 + dur);
out.connect(synth.channels[9].vol);
if (synth.reverb && spec.rev > 0.01) {
var send = ctx.createGain();
send.gain.value = spec.rev;
out.connect(send);
send.connect(synth.reverb);
this.send = send;
}
this.out = out;
this.sources = [];
if (spec.kind === 'kick' || spec.kind === 'tom') {
var o = ctx.createOscillator();
o.type = 'sine';
o.frequency.setValueAtTime(spec.f0, t0);
o.frequency.exponentialRampToValueAtTime(spec.f1, t0 + dur * 0.75);
o.connect(out);
o.start(t0);
o.stop(t0 + dur + 0.05);
this.sources.push(o);
} else {
var src = ctx.createBufferSource();
src.buffer = synth.noise;
src.loop = true;
var f = ctx.createBiquadFilter();
if (spec.kind === 'hat' || spec.kind === 'cymbal') {
f.type = 'highpass';
f.frequency.value = spec.freq;
} else {
f.type = 'bandpass';
f.frequency.value = spec.freq;
}
f.Q.value = spec.q || 0.8;
src.connect(f);
f.connect(out);
src.start(t0);
src.stop(t0 + dur + 0.05);
this.sources.push(src);
if (spec.body) { // 军鼓加一点鼓皮基音
var bo = ctx.createOscillator();
bo.type = 'triangle';
bo.frequency.setValueAtTime(spec.body, t0);
bo.frequency.exponentialRampToValueAtTime(spec.bf1, t0 + dur * 0.6);
var bg = ctx.createGain();
bg.gain.setValueAtTime(Math.max(amp * spec.bg, 0.0001), t0);
bg.gain.exponentialRampToValueAtTime(0.0005, t0 + dur * 0.8);
bo.connect(bg);
bg.connect(synth.channels[9].vol);
bo.start(t0);
bo.stop(t0 + dur + 0.05);
this.sources.push(bo);
}
}
this.stopTime = t0 + dur + 0.1;
}
DrumVoice.prototype.release = function () { /* 打击乐自动衰减 */ };
DrumVoice.prototype.cut = function (when) {
var t = clampTime(this.ctx, when);
holdParam(this.out.gain, t);
this.out.gain.linearRampToValueAtTime(0.0005, t + 0.02);
this.stopTime = t + 0.05;
for (var i = 0; i < this.sources.length; i++) {
try { this.sources[i].stop(this.stopTime); } catch (e) { /* 忽略 */ }
}
};
/* ============================= 合成器 ============================= */
function Synth(ctx, options) {
options = options || {};
this.ctx = ctx;
var master = ctx.createGain();
master.gain.value = options.volume == null ? 0.85 : options.volume;
var comp = ctx.createDynamicsCompressor();
comp.threshold.value = -10;
comp.knee.value = 24;
comp.ratio.value = 6;
comp.attack.value = 0.004;
comp.release.value = 0.22;
var analyser = ctx.createAnalyser();
analyser.fftSize = 1024;
analyser.smoothingTimeConstant = 0.7;
master.connect(comp);
comp.connect(analyser);
analyser.connect(ctx.destination);
this.master = master;
this.comp = comp;
this.analyser = analyser;
/* 混响总线(生成式脉冲响应,失败则自动关闭) */
this.reverb = null;
this.reverbGain = null;
try {
var conv = ctx.createConvolver();
conv.buffer = makeImpulse(ctx, 2.2, 2.6);
var wet = ctx.createGain();
wet.gain.value = 0.9;
conv.connect(wet);
wet.connect(master);
this.reverb = conv;
this.reverbGain = wet;
} catch (e) { this.reverb = null; }
/* 16 个通道总线:音量 -> 声像 -> 主输出 */
this.channels = [];
for (var i = 0; i < 16; i++) {
var vol = ctx.createGain();
vol.gain.value = 0.8;
var pan = null;
if (typeof ctx.createStereoPanner === 'function') {
pan = ctx.createStereoPanner();
vol.connect(pan);
pan.connect(master);
} else {
vol.connect(master);
}
this.channels.push({
vol: vol,
pan: pan,
base: 0.8, // CC7 通道音量
expr: 1 // CC11 表情
});
}
this.noise = makeNoiseBuffer(ctx, 2);
this.voices = [];
this.pending = {};
this.maxVoices = options.maxVoices || 40;
}
Synth.prototype.setVolume = function (v) {
var val = Math.max(0, Math.min(1.5, v));
this.master.gain.setTargetAtTime(val, this.ctx.currentTime, 0.02);
};
Synth.prototype.noteOn = function (channel, midi, velocity, when, program) {
if (!this.ctx) return;
if (velocity <= 0) { this.noteOff(channel, midi, when); return; }
var t = clampTime(this.ctx, when);
this._gc(t);
if (this.voices.length >= this.maxVoices) this._steal(t);
var voice;
if (channel === 9) {
voice = new DrumVoice(this, midi, velocity, t);
} else {
voice = new Voice(this, channel, midi, velocity, t, program || 0);
var k = channel * 128 + midi;
(this.pending[k] || (this.pending[k] = [])).push(voice);
}
this.voices.push(voice);
};
Synth.prototype.noteOff = function (channel, midi, when) {
if (channel === 9) return;
var k = channel * 128 + midi;
var arr = this.pending[k];
if (!arr || !arr.length) return;
var v = arr.shift();
if (!arr.length) delete this.pending[k];
v.release(clampTime(this.ctx, when));
};
Synth.prototype.handleCC = function (channel, number, value, when) {
var ch = this.channels[channel];
if (!ch) return;
var t = clampTime(this.ctx, when);
if (number === 7) {
ch.base = value / 127;
ch.vol.gain.setTargetAtTime(ch.base * ch.expr, t, 0.03);
} else if (number === 11) {
ch.expr = value / 127;
ch.vol.gain.setTargetAtTime(ch.base * ch.expr, t, 0.03);
} else if (number === 10 && ch.pan) {
ch.pan.pan.setTargetAtTime((value - 64) / 64, t, 0.03);
} else if (number === 120 || number === 123) {
this.panic(t);
}
};
/* 强制掐断所有正在发声的音符 */
Synth.prototype.panic = function (when) {
var t = when == null ? this.ctx.currentTime : when;
var list = this.voices.slice();
for (var i = 0; i < list.length; i++) {
try { list[i].cut(t); } catch (e) { /* 忽略 */ }
}
this.pending = {};
};
Synth.prototype.voiceCount = function () { return this.voices.length; };
/* 当前正在发声的 音高集合(用于可视化) */
Synth.prototype.activeNotes = function () {
var set = [];
for (var i = 0; i < this.voices.length; i++) {
if (!this.voices[i].released) set.push(this.voices[i].key);
}
return set;
};
Synth.prototype._gc = function (t) {
for (var i = this.voices.length - 1; i >= 0; i--) {
if (this.voices[i].stopTime <= t) this.voices.splice(i, 1);
}
for (var k in this.pending) {
var arr = this.pending[k];
for (var j = arr.length - 1; j >= 0; j--) if (arr[j].released) arr.splice(j, 1);
if (!arr.length) delete this.pending[k];
}
};
Synth.prototype._steal = function (t) {
var idx = -1;
for (var i = 0; i < this.voices.length; i++) {
if (!this.voices[i].released) { idx = i; break; }
}
if (idx === -1) idx = 0;
var v = this.voices.splice(idx, 1)[0];
if (v) { try { v.cut(t); } catch (e) { /* 忽略 */ } }
};
return {
Synth: Synth,
Voice: Voice,
FAMILIES: FAMILIES,
familyFor: familyFor,
drumSpec: drumSpec
};
});