js实现变声
使用Web Audio API实现变声
Web Audio API提供了音频处理能力,可以通过调整音频参数实现变声效果。以下是一个基础实现示例:
// 获取用户麦克风输入
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function(stream) {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const source = audioContext.createMediaStreamSource(stream);
// 创建变声效果节点
const pitchShift = audioContext.createScriptProcessor(4096, 1, 1);
pitchShift.onaudioprocess = function(e) {
const input = e.inputBuffer.getChannelData(0);
const output = e.outputBuffer.getChannelData(0);
// 调整音高(示例:提高一个八度)
for (let i = 0; i < input.length; i++) {
output[i] = input[Math.floor(i/2)]; // 简单降采样
}
};
source.connect(pitchShift);
pitchShift.connect(audioContext.destination);
})
.catch(console.error);
使用PitchShift算法
更专业的变声需要实现PitchShift算法。以下是使用Tuna.js库的示例:

// 引入Tuna.js库后
const audioContext = new AudioContext();
const tuna = new Tuna(audioContext);
const pitchShifter = new tuna.PitchShift({
pitch: 0.5, // 0.5=降八度, 1=原音, 2=升八度
windowSize: 1024,
overlapRatio: 0.5
});
// 连接音频源
source.connect(pitchShifter);
pitchShifter.connect(audioContext.destination);
使用现成的音频处理库
soundtouchjs是一个专门处理音频变调的库:

import { SoundTouch, SimpleFilter } from 'soundtouchjs';
const audioContext = new AudioContext();
const processor = audioContext.createScriptProcessor(4096, 1, 1);
const soundTouch = new SoundTouch();
const filter = new SimpleFilter(source, soundTouch);
// 设置变调参数
soundTouch.pitch = 1.2; // 1.0为原音
processor.onaudioprocess = function(e) {
filter.extract(e.outputBuffer, 4096);
};
source.connect(processor);
processor.connect(audioContext.destination);
调整音频参数实现不同效果
通过组合不同的音频节点可以创造多种变声效果:
// 机器人效果
const robotEffect = audioContext.createWaveShaper();
const distortionCurve = new Float32Array(44100);
for (let i = 0; i < 44100; i++) {
distortionCurve[i] = Math.sin(i / 100);
}
robotEffect.curve = distortionCurve;
// 低沉效果
const lowPass = audioContext.createBiquadFilter();
lowPass.type = "lowpass";
lowPass.frequency.value = 400;
// 连接效果链
source.connect(robotEffect);
robotEffect.connect(lowPass);
lowPass.connect(audioContext.destination);
实时变声录音实现
以下代码演示如何录制变声后的音频:
let mediaRecorder;
const chunks = [];
// 创建变声处理链后
const dest = audioContext.createMediaStreamDestination();
pitchShifter.connect(dest);
mediaRecorder = new MediaRecorder(dest.stream);
mediaRecorder.ondataavailable = (e) => chunks.push(e.data);
mediaRecorder.onstop = () => {
const blob = new Blob(chunks, { type: 'audio/webm' });
const url = URL.createObjectURL(blob);
// 处理录制结果
};
// 开始录制
mediaRecorder.start();
以上方法可以根据需要组合使用,通过调整参数值可以获得不同的变声效果。实际应用中可能需要考虑性能优化和更复杂的音频处理算法。






