feat: 初始化变声器项目仓库(逆向分析 + 实时变声 + PC 变声麦)
包含三大模块: - 逆向分析报告与实时变声方案设计文档 - realtime-voice:Android 实时变声(PSOLA 变调 + VTLP 共振峰 DSP 管线、Xposed 注入模块) - pc-voice:PC 变声麦工具(miniaudio 引擎、可配置 DSP 参数) 已通过 .gitignore 排除构建产物、本机工具链与本机路径配置。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
# pc-voice 变声麦(PC 实时男变女)
|
||||
|
||||
把电脑变成"女声发生器"。两种用法覆盖全部场景,**免 root、免解锁**:
|
||||
|
||||
| 方案 | 覆盖 | 需要的配件 |
|
||||
|---|---|---|
|
||||
| **方案一:PC 连手机** | 手机上**所有 App**(微信/QQ/Uki/Soul/赫兹/他趣…) | 音频线 + 转接线(~40 元) |
|
||||
| **方案二:PC 独立变声麦** | 微信/QQ **电脑版**语音通话 | VB-Cable 虚拟声卡(免费) |
|
||||
|
||||
## 工作原理
|
||||
|
||||
```
|
||||
你说话 → PC 麦克风 →[pc-voice 采集]→ DSP 变声(与手机 App 同一引擎)
|
||||
→ PC 音频输出 ──┬─(方案一)音频线 → 手机"耳机麦克风"输入
|
||||
└─(方案二)VB-Cable → 微信电脑版选作麦克风
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 方案一:PC 连手机(手机全 App 通用)
|
||||
|
||||
变声不发生在手机里——PC 把女声以"耳机麦克风信号"的身份喂给手机,手机上的任何 App 都以为你在用耳机麦。
|
||||
|
||||
### 接线图
|
||||
|
||||
```
|
||||
你说话 → PC 麦克风 ──→ [pc-voice --line-out] ──→ PC 耳机输出口(3.5mm)
|
||||
│
|
||||
3.5mm 对录线(TRS 两头)
|
||||
│
|
||||
CTIA 一分二转接线的"麦克风"口
|
||||
│
|
||||
手机耳机孔 ← 转接线"耳机"口(悬空不插)
|
||||
│
|
||||
手机上微信/QQ/Uki/Soul… 正常通话
|
||||
▼
|
||||
对方听到女声 🎉
|
||||
```
|
||||
|
||||
无耳机孔的手机(如一加 13):加一个**带麦克风输入的** USB-C 转 3.5mm 转接头,插在手机和转接线之间(便宜货很多只有输出没有输入,购买时认准"支持耳麦/麦克风")。
|
||||
|
||||
### 配件清单(合计 ~40 元)
|
||||
|
||||
| 配件 | 淘宝关键词 | 价格 |
|
||||
|---|---|---|
|
||||
| CTIA 一分二转接线(1分2,分出耳机+麦克风两个口) | 「CTIA 一分二 转接线 耳机麦克风」 | ~10元 |
|
||||
| 3.5mm 对录线(TRS 两头,直通线) | 「3.5mm 对录线 aux」 | ~10元 |
|
||||
| USB-C 转 3.5mm 转接头(仅无耳机孔手机需要) | 「一加13 转接头 支持耳麦」 | ~20元 |
|
||||
|
||||
### 步骤
|
||||
|
||||
1. 按图接好线(PC 耳机输出 → 对录线 → 转接线**麦克风口**;转接线耳机口悬空)
|
||||
2. 启动:`pc-voice.exe --line-out`(该模式跳过啸叫检查——线是插到手机里的,不会回授)
|
||||
3. **手机戴耳机听**(关键!手机外放的声音会被 PC 麦克风收进去形成回授回路)
|
||||
4. 手机打开微信/QQ 等,正常语音通话/发语音,对方听到女声
|
||||
5. 电平匹配:PC 系统音量 60% 起步,配合参数 `outputGain`(爆音就降,太小就升)
|
||||
|
||||
### 适用边界
|
||||
|
||||
需要人坐在电脑前(PC 是处理设备)。出门在外的移动场景本方案不覆盖。
|
||||
|
||||
---
|
||||
|
||||
## 方案二:PC 独立变声麦(微信/QQ 电脑版)
|
||||
|
||||
### 安装 VB-Cable(一次性,免费)
|
||||
|
||||
1. 官网 https://vb-audio.com/Cable/ 下载 VBCABLE_Driver_Pack
|
||||
2. 解压后右键 `VBCABLE_Setup_x64.exe` → 以管理员身份运行 → Install Driver → **重启电脑**
|
||||
|
||||
### 步骤
|
||||
|
||||
1. 直接运行 `pc-voice.exe`(自动选麦克风 + CABLE Input)
|
||||
2. 微信/QQ 电脑版:设置 → 语音 → 麦克风选 **「CABLE Output (VB-Audio Virtual Cable)」**
|
||||
3. 开始通话,对方听到女声 🎉
|
||||
|
||||
---
|
||||
|
||||
## 使用(两方案通用)
|
||||
|
||||
```
|
||||
pc-voice.exe --list # 列出所有音频设备
|
||||
pc-voice.exe --in 麦克风名字片段 --out 输出设备名字片段
|
||||
pc-voice.exe --config D:\path\voice_config.json # 指定参数配置
|
||||
```
|
||||
|
||||
**运行中快捷键**(全局生效,微信窗口在前面也行):
|
||||
|
||||
| 键 | 功能 |
|
||||
|---|---|
|
||||
| 1 / 2 / 3 / 4 | 预设:少女 / 御姐 / 萝莉 / 中性女 |
|
||||
| B | 旁路开关(干声/变声 A-B 对比) |
|
||||
| ESC | 退出 |
|
||||
|
||||
## 参数调试
|
||||
|
||||
**推荐:用参数控制台页面调**——双击打开 `config.html`(单文件静态页,离线可用):
|
||||
全部参数(音色/高级/预设/旁路)可视化调节,实时 JSON 预览,一键**下载 voice_config.json**
|
||||
放到 exe 旁即热生效;支持导入已有配置继续改、预设数值可编辑(对应快捷键 1~4)。
|
||||
|
||||
也可以直接改配置文件 `voice_config.json`(放在 exe 旁边,或 `--config` 指定),**与手机版格式完全一致**,运行中每 2 秒热加载——记事本改完保存即生效:
|
||||
|
||||
| 症状 | 调什么 |
|
||||
|---|---|
|
||||
| 像小黄人 | ↑ formantRatio(1.20→1.25) |
|
||||
| 不够亮 | ↑ pitchSemitones + ↑ eqGainDb |
|
||||
| 电音/机械感 | ↓ smoothing(0.05→0.02) |
|
||||
| 说话头尾被吞 | ↓ gateThreshold(0.006→0.003) |
|
||||
| 对方说太响/太轻 | outputGain(0.1~2.0) |
|
||||
|
||||
参数语义详见手机版 `VoiceConfig.java` 内注释。
|
||||
|
||||
## 常见问题
|
||||
|
||||
- **方案一对方听不到/声音小**:确认线插的是转接线的**麦克风**口;PC 系统音量和 `outputGain` 都往上抬
|
||||
- **方案一有回声**:手机必须戴耳机;不要用外放
|
||||
- **方案二微信里没声音**:确认微信麦克风选的是 CABLE Output;pc-voice 的"输出"必须是 CABLE Input
|
||||
- **有杂音/爆音**:关掉系统麦克风增强(声音设置→麦克风→属性→级别);`outputGain` 降到 1.0 以下
|
||||
- **延迟明显**:关掉其他占音频的软件;统计行"端到端"应在 70~80ms
|
||||
|
||||
## 构建(开发者)
|
||||
|
||||
```
|
||||
build.bat # 需要 D:\voiceScript\.toolchain\w64devkit(便携 GCC)
|
||||
```
|
||||
|
||||
DSP 引擎源码与 Android 版共用(`realtime-voice/app/src/main/cpp/`),一份代码三处部署(测试 App / Xposed 模块 / PC 工具)。
|
||||
@@ -0,0 +1,20 @@
|
||||
@echo off
|
||||
rem PC 变声麦构建脚本(w64devkit 便携 GCC,产物 pc-voice.exe)
|
||||
setlocal
|
||||
set GCC=D:\voiceScript\.toolchain\w64devkit\bin\g++.exe
|
||||
set SHARED=D:\voiceScript\realtime-voice\app\src\main\cpp
|
||||
|
||||
"%GCC%" -O2 -std=c++17 -Wall ^
|
||||
-I"%SHARED%" -Ilib ^
|
||||
main.cpp ^
|
||||
"%SHARED%\psola.cpp" ^
|
||||
"%SHARED%\dsp_pipeline.cpp" ^
|
||||
-o pc-voice.exe ^
|
||||
-lole32 -lwinmm -luuid -ladvapi32
|
||||
|
||||
if %errorlevel% neq 0 (
|
||||
echo 构建失败
|
||||
exit /b 1
|
||||
)
|
||||
echo 构建成功: pc-voice.exe
|
||||
endlocal
|
||||
@@ -0,0 +1,130 @@
|
||||
#pragma once
|
||||
|
||||
// voice_config.json 极简解析器(与 Android 版配置格式完全一致)
|
||||
// 只解析 "params" 段的扁平键值;键按首次出现匹配(params 段在文件中先于 presets)
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
struct VoiceCfg {
|
||||
float pitchSemitones = 9.f;
|
||||
float formantRatio = 1.20f;
|
||||
float strength = 1.f;
|
||||
float eqFreqHz = 3000.f;
|
||||
float eqGainDb = 3.f;
|
||||
float gateThreshold = 0.006f;
|
||||
float f0MinHz = 65.f;
|
||||
float f0MaxHz = 500.f;
|
||||
float smoothing = 0.05f;
|
||||
float outputGain = 1.f;
|
||||
bool bypass = false;
|
||||
// 目标音高模式:输出 f0 锚定 targetF0Hz(深沉嗓音自动多补)
|
||||
bool targetMode = false;
|
||||
float targetF0Hz = 205.f;
|
||||
// 预设 {音调半音, 共振峰比},顺序:少女 / 御姐 / 萝莉 / 中性女
|
||||
float presets[4][2] = {
|
||||
{9.f, 1.20f},
|
||||
{7.f, 1.15f},
|
||||
{12.f, 1.25f},
|
||||
{5.f, 1.12f},
|
||||
};
|
||||
};
|
||||
|
||||
namespace cfgdetail {
|
||||
|
||||
inline bool findValue(const std::string& text, const char* key, std::string& out) {
|
||||
std::string pat = std::string("\"") + key + "\"";
|
||||
size_t pos = text.find(pat);
|
||||
if (pos == std::string::npos) return false;
|
||||
pos = text.find(':', pos + pat.size());
|
||||
if (pos == std::string::npos) return false;
|
||||
++pos;
|
||||
while (pos < text.size() && (text[pos] == ' ' || text[pos] == '\t')) ++pos;
|
||||
size_t end = pos;
|
||||
while (end < text.size() && text[end] != ',' && text[end] != '}' &&
|
||||
text[end] != '\n' && text[end] != '\r') {
|
||||
++end;
|
||||
}
|
||||
out = text.substr(pos, end - pos);
|
||||
// 去掉首尾空白
|
||||
while (!out.empty() && (out.back() == ' ' || out.back() == '\t')) out.pop_back();
|
||||
return !out.empty();
|
||||
}
|
||||
|
||||
inline float parseFloat(const std::string& text, const char* key, float def) {
|
||||
std::string v;
|
||||
if (!findValue(text, key, v)) return def;
|
||||
return (float)atof(v.c_str());
|
||||
}
|
||||
|
||||
inline bool parseBool(const std::string& text, const char* key, bool def) {
|
||||
std::string v;
|
||||
if (!findValue(text, key, v)) return def;
|
||||
return v.find("true") != std::string::npos;
|
||||
}
|
||||
|
||||
// 取第 n 次出现的键值(用于 presets 数组里的成对数值,n 从 0 起)
|
||||
inline float findNthFloat(const std::string& text, const char* key, int n, float def) {
|
||||
std::string pat = std::string("\"") + key + "\"";
|
||||
size_t pos = std::string::npos;
|
||||
for (int i = 0; i <= n; ++i) {
|
||||
pos = text.find(pat, pos + 1);
|
||||
if (pos == std::string::npos) return def;
|
||||
}
|
||||
pos = text.find(':', pos + pat.size());
|
||||
if (pos == std::string::npos) return def;
|
||||
++pos;
|
||||
while (pos < text.size() && (text[pos] == ' ' || text[pos] == '\t')) ++pos;
|
||||
return (float)atof(text.c_str() + pos);
|
||||
}
|
||||
|
||||
} // namespace cfgdetail
|
||||
|
||||
// 读取配置;失败时保留默认值并返回 false
|
||||
inline bool loadConfig(const std::string& path, VoiceCfg& c) {
|
||||
FILE* f = fopen(path.c_str(), "rb");
|
||||
if (!f) return false;
|
||||
fseek(f, 0, SEEK_END);
|
||||
long len = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (len <= 0 || len > 1024 * 1024) {
|
||||
fclose(f);
|
||||
return false;
|
||||
}
|
||||
std::string text((size_t)len, '\0');
|
||||
size_t rd = fread(&text[0], 1, (size_t)len, f);
|
||||
fclose(f);
|
||||
text.resize(rd);
|
||||
|
||||
// params 段与 presets 段分开解析(键按段内出现顺序匹配)
|
||||
const size_t cut = text.find("\"presets\"");
|
||||
std::string paramsPart = (cut == std::string::npos) ? text : text.substr(0, cut);
|
||||
std::string presetsPart = (cut == std::string::npos) ? "" : text.substr(cut);
|
||||
|
||||
{
|
||||
using namespace cfgdetail;
|
||||
c.pitchSemitones = parseFloat(paramsPart, "pitchSemitones", c.pitchSemitones);
|
||||
c.formantRatio = parseFloat(paramsPart, "formantRatio", c.formantRatio);
|
||||
c.strength = parseFloat(paramsPart, "strength", c.strength);
|
||||
c.eqFreqHz = parseFloat(paramsPart, "eqFreqHz", c.eqFreqHz);
|
||||
c.eqGainDb = parseFloat(paramsPart, "eqGainDb", c.eqGainDb);
|
||||
c.gateThreshold = parseFloat(paramsPart, "gateThreshold", c.gateThreshold);
|
||||
c.f0MinHz = parseFloat(paramsPart, "f0MinHz", c.f0MinHz);
|
||||
c.f0MaxHz = parseFloat(paramsPart, "f0MaxHz", c.f0MaxHz);
|
||||
c.smoothing = parseFloat(paramsPart, "smoothing", c.smoothing);
|
||||
c.outputGain = parseFloat(paramsPart, "outputGain", c.outputGain);
|
||||
c.bypass = parseBool(paramsPart, "bypass", c.bypass);
|
||||
c.targetMode = parseBool(paramsPart, "targetMode", c.targetMode);
|
||||
c.targetF0Hz = parseFloat(paramsPart, "targetF0Hz", c.targetF0Hz);
|
||||
|
||||
// presets:按出现顺序成对读取(少女/御姐/萝莉/中性女)
|
||||
if (!presetsPart.empty()) {
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
c.presets[i][0] = findNthFloat(presetsPart, "pitchSemitones", i, c.presets[i][0]);
|
||||
c.presets[i][1] = findNthFloat(presetsPart, "formantRatio", i, c.presets[i][1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>pc-voice 参数控制台</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f1115; --panel: #181c22; --panel2: #1f242c;
|
||||
--text: #e8eaed; --muted: #9aa3af; --accent: #2dd4bf; --accent2: #f59e0b;
|
||||
--border: #2a313b; --track: #2a313b;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
background: var(--bg); color: var(--text);
|
||||
font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
|
||||
padding: 24px; line-height: 1.6;
|
||||
}
|
||||
header { margin-bottom: 20px; }
|
||||
h1 { font-size: 22px; font-weight: 700; }
|
||||
h1 .tag { color: var(--accent); }
|
||||
.sub { color: var(--muted); font-size: 13px; margin-top: 4px; }
|
||||
.layout { display: grid; grid-template-columns: 1fr 380px; gap: 20px; align-items: start; }
|
||||
@media (max-width: 960px) { .layout { grid-template-columns: 1fr; } }
|
||||
|
||||
.card {
|
||||
background: var(--panel); border: 1px solid var(--border);
|
||||
border-radius: 12px; padding: 18px 20px; margin-bottom: 16px;
|
||||
}
|
||||
.card h2 { font-size: 15px; margin-bottom: 12px; color: var(--accent); font-weight: 600; }
|
||||
.card h2 small { color: var(--muted); font-weight: 400; font-size: 12px; }
|
||||
|
||||
.row { display: grid; grid-template-columns: 190px 1fr 92px; gap: 12px; align-items: center; padding: 7px 0; }
|
||||
.row .name { font-size: 13px; }
|
||||
.row .name .hint { display: block; color: var(--muted); font-size: 11px; }
|
||||
.row .val { font-family: Consolas, monospace; font-size: 13px; color: var(--accent2); text-align: right; }
|
||||
input[type=range] { width: 100%; accent-color: var(--accent); height: 22px; cursor: pointer; }
|
||||
|
||||
.switch { display: flex; align-items: center; gap: 10px; padding: 8px 0; cursor: pointer; user-select: none; }
|
||||
.switch input { width: 18px; height: 18px; accent-color: var(--accent); cursor: pointer; }
|
||||
|
||||
.presets { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.preset {
|
||||
background: var(--panel2); border: 1px solid var(--border); border-radius: 10px;
|
||||
padding: 12px; cursor: pointer; transition: border-color .15s;
|
||||
}
|
||||
.preset:hover { border-color: var(--accent); }
|
||||
.preset .pname { font-size: 14px; font-weight: 600; margin-bottom: 8px; }
|
||||
.preset .prow { display: flex; gap: 6px; align-items: center; font-size: 11px; color: var(--muted); margin-top: 4px; }
|
||||
.preset input {
|
||||
width: 62px; background: var(--bg); color: var(--text); border: 1px solid var(--border);
|
||||
border-radius: 6px; padding: 3px 6px; font-family: Consolas, monospace; font-size: 12px;
|
||||
}
|
||||
.preset .apply { margin-top: 8px; font-size: 11px; color: var(--accent); }
|
||||
|
||||
pre#preview {
|
||||
background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 12px; font-family: Consolas, monospace; font-size: 11px;
|
||||
max-height: 320px; overflow: auto; white-space: pre-wrap; color: #b7c3d0;
|
||||
}
|
||||
|
||||
.btns { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
|
||||
button {
|
||||
background: var(--accent); color: #04211d; border: 0; border-radius: 8px;
|
||||
padding: 9px 16px; font-size: 13px; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
button:hover { filter: brightness(1.1); }
|
||||
button.ghost { background: var(--panel2); color: var(--text); border: 1px solid var(--border); }
|
||||
.tip { color: var(--muted); font-size: 12px; margin-top: 10px; }
|
||||
.tip code { background: var(--panel2); padding: 1px 6px; border-radius: 4px; color: var(--accent2); }
|
||||
|
||||
details { margin-top: 8px; }
|
||||
summary { cursor: pointer; font-size: 13px; color: var(--accent); }
|
||||
table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 12px; }
|
||||
th, td { border: 1px solid var(--border); padding: 7px 10px; text-align: left; }
|
||||
th { background: var(--panel2); color: var(--muted); font-weight: 600; }
|
||||
.ok { color: var(--accent); font-size: 12px; min-height: 18px; margin-top: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<h1>pc-voice <span class="tag">参数控制台</span></h1>
|
||||
<div class="sub">所有可配置项可视化调校 → 下载 voice_config.json 放到 pc-voice.exe 同目录 → 工具 2 秒内热生效(无需重启)</div>
|
||||
</header>
|
||||
|
||||
<div class="layout">
|
||||
<main>
|
||||
<div class="card">
|
||||
<h2>音色参数 <small>决定"像不像女声"</small></h2>
|
||||
<div class="row">
|
||||
<div class="name">音调<span class="hint">男变女约 +5~+12 半音(目标模式下失效)</span></div>
|
||||
<input type="range" id="pitchSemitones" min="0" max="24" step="0.5">
|
||||
<div class="val" id="pitchSemitones_v"></div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="targetMode">
|
||||
<span>目标音高模式(输出锚定下方 Hz,深沉嗓音自动多补,推荐)</span>
|
||||
</label>
|
||||
<div class="row">
|
||||
<div class="name">目标音高<span class="hint">御姐≈205,少女≈240,萝莉≈280</span></div>
|
||||
<input type="range" id="targetF0Hz" min="150" max="300" step="5">
|
||||
<div class="val" id="targetF0Hz_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">共振峰搬移<span class="hint">1.15~1.25 自然区间,防小黄人核心</span></div>
|
||||
<input type="range" id="formantRatio" min="1" max="1.4" step="0.01">
|
||||
<div class="val" id="formantRatio_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">效果强度<span class="hint">整体效果按比例缩放</span></div>
|
||||
<input type="range" id="strength" min="0" max="1" step="0.01">
|
||||
<div class="val" id="strength_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">输出增益<span class="hint">爆音就降,太小就升</span></div>
|
||||
<input type="range" id="outputGain" min="0.1" max="2" step="0.05">
|
||||
<div class="val" id="outputGain_v"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>高级参数 <small>音质微调(不对劲时查下方速查表)</small></h2>
|
||||
<div class="row">
|
||||
<div class="name">亮度 EQ 频点</div>
|
||||
<input type="range" id="eqFreqHz" min="500" max="8000" step="100">
|
||||
<div class="val" id="eqFreqHz_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">亮度 EQ 增益<span class="hint">女声"空气感"</span></div>
|
||||
<input type="range" id="eqGainDb" min="0" max="10" step="0.5">
|
||||
<div class="val" id="eqGainDb_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">噪声门阈值<span class="hint">越低越灵敏,防切字</span></div>
|
||||
<input type="range" id="gateThreshold" min="0" max="0.01" step="0.0005">
|
||||
<div class="val" id="gateThreshold_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">基频检测下限</div>
|
||||
<input type="range" id="f0MinHz" min="40" max="200" step="5">
|
||||
<div class="val" id="f0MinHz_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">基频检测上限</div>
|
||||
<input type="range" id="f0MaxHz" min="300" max="800" step="10">
|
||||
<div class="val" id="f0MaxHz_v"></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">参数平滑<span class="hint">越小越平滑,防颤音</span></div>
|
||||
<input type="range" id="smoothing" min="0.001" max="0.1" step="0.001">
|
||||
<div class="val" id="smoothing_v"></div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="bypass">
|
||||
<span>旁路直通(干声 A/B 对比,同延迟)</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>症状速查表 <small>听感不对就查这里</small></h2>
|
||||
<table>
|
||||
<tr><th>症状</th><th>调什么</th></tr>
|
||||
<tr><td>像小黄人 / 卡通音</td><td>↑ 共振峰搬移(1.20→1.25),别只加音调</td></tr>
|
||||
<tr><td>还是男声 / 不够亮</td><td>↑ 音调(+9→+12)+ ↑ EQ 增益</td></tr>
|
||||
<tr><td>电音 / 机械感</td><td>↓ 参数平滑(0.05→0.02);音调降到 +7</td></tr>
|
||||
<tr><td>说话头尾被吞</td><td>↓ 噪声门阈值(0.006→0.003)</td></tr>
|
||||
<tr><td>颤音 / 变调抖动</td><td>↓ 参数平滑(0.05→0.02)</td></tr>
|
||||
<tr><td>变调飘忽不稳</td><td>收窄基频范围(如 80~350)</td></tr>
|
||||
<tr><td>对方说太响 / 太轻</td><td>输出增益(0.1~2.0)</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<aside>
|
||||
<div class="card">
|
||||
<h2>预设 <small>点卡片立即应用,数值可改</small></h2>
|
||||
<div class="presets" id="presets"></div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>voice_config.json</h2>
|
||||
<pre id="preview"></pre>
|
||||
<div class="btns">
|
||||
<button onclick="downloadCfg()">⬇ 下载配置</button>
|
||||
<button class="ghost" onclick="copyCfg()">复制 JSON</button>
|
||||
<button class="ghost" onclick="document.getElementById('fileIn').click()">导入配置</button>
|
||||
<button class="ghost" onclick="resetCfg()">恢复默认</button>
|
||||
<input type="file" id="fileIn" accept=".json" style="display:none" onchange="importCfg(this)">
|
||||
</div>
|
||||
<div class="ok" id="okMsg"></div>
|
||||
<div class="tip">
|
||||
下载后把 <code>voice_config.json</code> 放到 <code>pc-voice.exe</code> 同目录(或 <code>--config</code> 指定路径),
|
||||
工具每 2 秒检测文件变化自动生效——<b>改完保存即变声,不用重启</b>。<br><br>
|
||||
预设对应运行中快捷键 <code>1/2/3/4</code>,这里改了数值,快捷键就是新值。
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const DEFAULTS = {
|
||||
pitchSemitones: 9, formantRatio: 1.20, strength: 1,
|
||||
eqFreqHz: 3000, eqGainDb: 3, gateThreshold: 0.006,
|
||||
f0MinHz: 65, f0MaxHz: 500, smoothing: 0.05,
|
||||
outputGain: 1, bypass: false,
|
||||
targetMode: true, targetF0Hz: 205,
|
||||
presets: [
|
||||
{ name: "少女", pitchSemitones: 9, formantRatio: 1.20 },
|
||||
{ name: "御姐", pitchSemitones: 7, formantRatio: 1.15 },
|
||||
{ name: "萝莉", pitchSemitones: 12, formantRatio: 1.25 },
|
||||
{ name: "中性女", pitchSemitones: 5, formantRatio: 1.12 },
|
||||
],
|
||||
};
|
||||
|
||||
let cfg = structuredClone(DEFAULTS);
|
||||
|
||||
const FMT = {
|
||||
pitchSemitones: v => "+" + Number(v).toFixed(1) + " 半音",
|
||||
formantRatio: v => "×" + Number(v).toFixed(2),
|
||||
strength: v => Math.round(v * 100) + "%",
|
||||
outputGain: v => "×" + Number(v).toFixed(2),
|
||||
eqFreqHz: v => Number(v).toFixed(0) + " Hz",
|
||||
eqGainDb: v => "+" + Number(v).toFixed(1) + " dB",
|
||||
gateThreshold: v => Number(v).toFixed(4),
|
||||
f0MinHz: v => Number(v).toFixed(0) + " Hz",
|
||||
f0MaxHz: v => Number(v).toFixed(0) + " Hz",
|
||||
smoothing: v => Number(v).toFixed(3),
|
||||
targetF0Hz: v => Number(v).toFixed(0) + " Hz",
|
||||
};
|
||||
|
||||
const SLIDER_KEYS = Object.keys(FMT);
|
||||
|
||||
function buildSliders() {
|
||||
for (const k of SLIDER_KEYS) {
|
||||
const el = document.getElementById(k);
|
||||
el.value = cfg[k];
|
||||
el.addEventListener("input", () => {
|
||||
cfg[k] = parseFloat(el.value);
|
||||
render();
|
||||
});
|
||||
}
|
||||
document.getElementById("bypass").addEventListener("change", e => {
|
||||
cfg.bypass = e.target.checked;
|
||||
render();
|
||||
});
|
||||
document.getElementById("targetMode").addEventListener("change", e => {
|
||||
cfg.targetMode = e.target.checked;
|
||||
render();
|
||||
});
|
||||
}
|
||||
|
||||
function buildPresets() {
|
||||
const wrap = document.getElementById("presets");
|
||||
wrap.innerHTML = "";
|
||||
cfg.presets.forEach((p, i) => {
|
||||
const div = document.createElement("div");
|
||||
div.className = "preset";
|
||||
div.innerHTML = `
|
||||
<div class="pname">${p.name}</div>
|
||||
<div class="prow">音调 <input type="number" min="0" max="24" step="0.5" value="${p.pitchSemitones}" data-i="${i}" data-k="pitchSemitones"></div>
|
||||
<div class="prow">共振峰 <input type="number" min="1" max="1.4" step="0.01" value="${p.formantRatio}" data-i="${i}" data-k="formantRatio"></div>
|
||||
<div class="apply">▶ 点卡片应用此预设</div>`;
|
||||
div.addEventListener("click", () => applyPreset(i));
|
||||
div.querySelectorAll("input").forEach(inp => {
|
||||
inp.addEventListener("click", e => e.stopPropagation());
|
||||
inp.addEventListener("input", e => {
|
||||
cfg.presets[i][e.target.dataset.k] = parseFloat(e.target.value) || 0;
|
||||
render();
|
||||
});
|
||||
});
|
||||
wrap.appendChild(div);
|
||||
});
|
||||
}
|
||||
|
||||
function applyPreset(i) {
|
||||
const p = cfg.presets[i];
|
||||
cfg.pitchSemitones = p.pitchSemitones;
|
||||
cfg.formantRatio = p.formantRatio;
|
||||
document.getElementById("pitchSemitones").value = cfg.pitchSemitones;
|
||||
document.getElementById("formantRatio").value = cfg.formantRatio;
|
||||
render();
|
||||
msg("已应用预设:" + p.name);
|
||||
}
|
||||
|
||||
function buildJson() {
|
||||
return JSON.stringify({
|
||||
params: {
|
||||
pitchSemitones: cfg.pitchSemitones,
|
||||
formantRatio: cfg.formantRatio,
|
||||
strength: cfg.strength,
|
||||
eqFreqHz: cfg.eqFreqHz,
|
||||
eqGainDb: cfg.eqGainDb,
|
||||
gateThreshold: cfg.gateThreshold,
|
||||
f0MinHz: cfg.f0MinHz,
|
||||
f0MaxHz: cfg.f0MaxHz,
|
||||
smoothing: cfg.smoothing,
|
||||
bypass: cfg.bypass,
|
||||
outputGain: cfg.outputGain,
|
||||
targetMode: cfg.targetMode,
|
||||
targetF0Hz: cfg.targetF0Hz,
|
||||
},
|
||||
presets: cfg.presets.map(p => ({
|
||||
name: p.name,
|
||||
pitchSemitones: p.pitchSemitones,
|
||||
formantRatio: p.formantRatio,
|
||||
})),
|
||||
version: 1,
|
||||
}, null, 2);
|
||||
}
|
||||
|
||||
function render() {
|
||||
for (const k of SLIDER_KEYS) {
|
||||
document.getElementById(k + "_v").textContent = FMT[k](cfg[k]);
|
||||
document.getElementById(k).value = cfg[k];
|
||||
}
|
||||
document.getElementById("bypass").checked = cfg.bypass;
|
||||
document.getElementById("targetMode").checked = cfg.targetMode;
|
||||
document.getElementById("preview").textContent = buildJson();
|
||||
}
|
||||
|
||||
function msg(t) {
|
||||
const el = document.getElementById("okMsg");
|
||||
el.textContent = t;
|
||||
setTimeout(() => { if (el.textContent === t) el.textContent = ""; }, 3000);
|
||||
}
|
||||
|
||||
function downloadCfg() {
|
||||
const blob = new Blob([buildJson()], { type: "application/json" });
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = "voice_config.json";
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
msg("已下载 voice_config.json → 放到 pc-voice.exe 同目录");
|
||||
}
|
||||
|
||||
function copyCfg() {
|
||||
navigator.clipboard.writeText(buildJson()).then(() => msg("JSON 已复制到剪贴板"));
|
||||
}
|
||||
|
||||
function importCfg(input) {
|
||||
const f = input.files[0];
|
||||
if (!f) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
try {
|
||||
const j = JSON.parse(reader.result);
|
||||
const p = j.params || {};
|
||||
for (const k of SLIDER_KEYS) {
|
||||
if (typeof p[k] === "number") cfg[k] = p[k];
|
||||
}
|
||||
if (typeof p.bypass === "boolean") cfg.bypass = p.bypass;
|
||||
if (typeof p.targetMode === "boolean") cfg.targetMode = p.targetMode;
|
||||
if (Array.isArray(j.presets)) {
|
||||
j.presets.slice(0, 4).forEach((sp, i) => {
|
||||
if (typeof sp.pitchSemitones === "number") cfg.presets[i].pitchSemitones = sp.pitchSemitones;
|
||||
if (typeof sp.formantRatio === "number") cfg.presets[i].formantRatio = sp.formantRatio;
|
||||
if (typeof sp.name === "string" && sp.name) cfg.presets[i].name = sp.name;
|
||||
});
|
||||
}
|
||||
buildPresets();
|
||||
render();
|
||||
msg("配置已导入");
|
||||
} catch (e) {
|
||||
msg("导入失败:不是合法的 voice_config.json");
|
||||
}
|
||||
input.value = "";
|
||||
};
|
||||
reader.readAsText(f);
|
||||
}
|
||||
|
||||
function resetCfg() {
|
||||
cfg = structuredClone(DEFAULTS);
|
||||
buildPresets();
|
||||
render();
|
||||
msg("已恢复默认参数");
|
||||
}
|
||||
|
||||
buildSliders();
|
||||
buildPresets();
|
||||
render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,244 @@
|
||||
// engine_test.cpp — 引擎离线自测台(不需要声卡,不需要人耳)
|
||||
//
|
||||
// 流程:合成已知参数的男声(f0≈105Hz + /a/ 元音共振峰 730/1090/2440Hz)
|
||||
// → 走完整 DSP 管线(与实时版同一份代码)
|
||||
// → 客观测量输出(基频/共振峰/高频清晰度/谐波锐度)
|
||||
// → 输出 test/in.wav 与 test/out.wav 供人耳 A/B
|
||||
//
|
||||
// 编译:g++ -O2 -std=c++17 -I../realtime-voice/app/src/main/cpp engine_test.cpp
|
||||
// ../realtime-voice/app/src/main/cpp/psola.cpp ../realtime-voice/app/src/main/cpp/dsp_pipeline.cpp -o engine_test.exe
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <direct.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
#include "dsp_pipeline.h"
|
||||
|
||||
static const double kSr = 48000.0;
|
||||
static const double kPi = 3.14159265358979;
|
||||
|
||||
// ---------- 合成:男声 /a/ 元音 ----------
|
||||
// 脉冲串(f0 带轻微颤音)→ 三个全极点共振峰滤波器
|
||||
static void synthMaleVowel(std::vector<float>& out, double dur) {
|
||||
const int n = (int)(dur * kSr);
|
||||
out.assign((size_t)n, 0.f);
|
||||
|
||||
// 1) 基频脉冲串(100→108Hz 缓升 + 3Hz 颤音)
|
||||
double phase = 0.0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const double t = (double)i / kSr;
|
||||
const double f0 = 100.0 + 8.0 * t / dur + 3.0 * std::sin(2.0 * kPi * 3.0 * t);
|
||||
phase += f0 / kSr;
|
||||
if (phase >= 1.0) {
|
||||
phase -= 1.0;
|
||||
out[(size_t)i] = 1.0f;
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 共振峰(全极点二阶谐振器级联,/a/: F1=730 F2=1090 F3=2440)
|
||||
struct Formant { double f, bw; };
|
||||
const Formant fs[3] = {{730, 90}, {1090, 110}, {2440, 160}};
|
||||
for (const auto& fm : fs) {
|
||||
const double r = std::exp(-kPi * fm.bw / kSr);
|
||||
const double th = 2.0 * kPi * fm.f / kSr;
|
||||
const double a1 = 2.0 * r * std::cos(th);
|
||||
const double a2 = -r * r;
|
||||
const double g = 1.0 - r;
|
||||
double y1 = 0, y2 = 0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const double y = g * (double)out[(size_t)i] + a1 * y1 + a2 * y2;
|
||||
y2 = y1;
|
||||
y1 = y;
|
||||
out[(size_t)i] = (float)y;
|
||||
}
|
||||
}
|
||||
|
||||
// 3) 幅度包络(淡入淡出防爆音)+ 电平归一
|
||||
float peak = 0.f;
|
||||
for (float v : out) peak = std::max(peak, std::fabs(v));
|
||||
if (peak > 0.f) {
|
||||
for (auto& v : out) v *= 0.5f / peak;
|
||||
}
|
||||
const int fade = (int)(0.05 * kSr);
|
||||
for (int i = 0; i < fade; ++i) {
|
||||
const float w = (float)i / (float)fade;
|
||||
out[(size_t)i] *= w;
|
||||
out[(size_t)(n - 1 - i)] *= w;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 测量工具 ----------
|
||||
// 自相关法测基频(先低通 800Hz 去掉高频谐波对自相关峰值的干扰)
|
||||
static double measureF0(const float* x, int n, double sr) {
|
||||
std::vector<float> buf((size_t)n);
|
||||
double lp = 0.0;
|
||||
const double a = std::exp(-2.0 * kPi * 800.0 / sr);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
lp = (1.0 - a) * x[i] + a * lp;
|
||||
buf[(size_t)i] = (float)lp;
|
||||
}
|
||||
double mean = 0.0;
|
||||
for (int i = 0; i < n; ++i) mean += buf[(size_t)i];
|
||||
mean /= n;
|
||||
for (int i = 0; i < n; ++i) buf[(size_t)i] = (float)(buf[(size_t)i] - mean);
|
||||
|
||||
const int lagMin = (int)(sr / 400.0);
|
||||
const int lagMax = std::min((int)(sr / 60.0), n / 2);
|
||||
double best = -1.0;
|
||||
int bestLag = 0;
|
||||
for (int lag = lagMin; lag <= lagMax; ++lag) {
|
||||
double s = 0.0;
|
||||
for (int i = 0; i + lag < n; ++i) s += (double)buf[(size_t)i] * buf[(size_t)(i + lag)];
|
||||
s /= (n - lag);
|
||||
if (s > best) {
|
||||
best = s;
|
||||
bestLag = lag;
|
||||
}
|
||||
}
|
||||
return bestLag > 0 ? sr / (double)bestLag : 0.0;
|
||||
}
|
||||
|
||||
// Goertzel 单频幅度
|
||||
static double goertzel(const std::vector<float>& x, double f, double sr) {
|
||||
const double w = 2.0 * kPi * f / sr;
|
||||
const double coeff = 2.0 * std::cos(w);
|
||||
double s1 = 0, s2 = 0;
|
||||
for (float v : x) {
|
||||
const double s0 = (double)v + coeff * s1 - s2;
|
||||
s2 = s1;
|
||||
s1 = s0;
|
||||
}
|
||||
const double power = s1 * s1 + s2 * s2 - coeff * s1 * s2;
|
||||
return std::sqrt(std::max(0.0, power)) / ((double)x.size() / 2.0);
|
||||
}
|
||||
|
||||
// 谐波噪声比 HNR(dB):谐波处能量 vs 泛音间能量——"清晰/模糊"的正确度量
|
||||
static double hnrDb(const std::vector<float>& x, double f0, double sr) {
|
||||
if (f0 < 20.0) return 0.0;
|
||||
double h = 0.0, n = 0.0;
|
||||
int ch = 0, cn = 0;
|
||||
for (int k = 1; k <= 12; ++k) {
|
||||
const double fh = f0 * k;
|
||||
if (fh > 5000.0) break;
|
||||
h += goertzel(x, fh, sr);
|
||||
++ch;
|
||||
const double fn = f0 * (k + 0.5);
|
||||
if (fn <= 5000.0) {
|
||||
n += goertzel(x, fn, sr);
|
||||
++cn;
|
||||
}
|
||||
}
|
||||
if (ch == 0 || cn == 0) return 0.0;
|
||||
const double mh = h / ch, mn = n / cn;
|
||||
return 20.0 * std::log10(mh / std::max(1e-9, mn));
|
||||
}
|
||||
|
||||
// 谱包络共振峰:粗网格幅度谱 → 平滑 → 找包络峰(避开谐波栅格的干扰)
|
||||
static double envelopePeak(const std::vector<float>& x, double fLo, double fHi, double sr) {
|
||||
std::vector<double> mag;
|
||||
for (double f = fLo; f <= fHi; f += 20.0) mag.push_back(goertzel(x, f, sr));
|
||||
// 5 点平滑成包络
|
||||
std::vector<double> env(mag.size(), 0.0);
|
||||
for (size_t i = 0; i < mag.size(); ++i) {
|
||||
double s = 0.0;
|
||||
int c = 0;
|
||||
for (int d = -2; d <= 2; ++d) {
|
||||
const int j = (int)i + d;
|
||||
if (j >= 0 && j < (int)mag.size()) {
|
||||
s += mag[(size_t)j];
|
||||
++c;
|
||||
}
|
||||
}
|
||||
env[i] = s / c;
|
||||
}
|
||||
size_t best = 0;
|
||||
for (size_t i = 1; i < env.size(); ++i) {
|
||||
if (env[i] > env[best]) best = i;
|
||||
}
|
||||
return fLo + 20.0 * (double)best;
|
||||
}
|
||||
|
||||
static void writeWav(const std::string& path, const std::vector<float>& x, double sr) {
|
||||
FILE* f = fopen(path.c_str(), "wb");
|
||||
if (!f) return;
|
||||
const int n = (int)x.size();
|
||||
const int dataBytes = n * 2;
|
||||
const int srI = (int)sr;
|
||||
unsigned char hdr[44];
|
||||
memcpy(hdr, "RIFF", 4);
|
||||
*(unsigned int*)(hdr + 4) = (unsigned)(36 + dataBytes);
|
||||
memcpy(hdr + 8, "WAVEfmt ", 8);
|
||||
*(unsigned int*)(hdr + 16) = 16;
|
||||
*(unsigned short*)(hdr + 20) = 1;
|
||||
*(unsigned short*)(hdr + 22) = 1;
|
||||
*(unsigned int*)(hdr + 24) = (unsigned)srI;
|
||||
*(unsigned int*)(hdr + 28) = (unsigned)(srI * 2);
|
||||
*(unsigned short*)(hdr + 32) = 2;
|
||||
*(unsigned short*)(hdr + 34) = 16;
|
||||
memcpy(hdr + 36, "data", 4);
|
||||
*(unsigned int*)(hdr + 40) = (unsigned)dataBytes;
|
||||
fwrite(hdr, 1, 44, f);
|
||||
for (float v : x) {
|
||||
float c = std::max(-1.f, std::min(1.f, v));
|
||||
short s = (short)(c * 32767.f);
|
||||
fwrite(&s, 2, 1, f);
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
int main() {
|
||||
printf("==== 引擎离线自测 ====\n");
|
||||
_mkdir("test");
|
||||
|
||||
// 1) 合成男声(含 0.3s 静音段测门限)
|
||||
std::vector<float> input;
|
||||
synthMaleVowel(input, 2.0);
|
||||
|
||||
// 2) 走完整管线(与实时版同一份代码,参数=当前御姐配置)
|
||||
DspPipeline pipe;
|
||||
pipe.setup((float)kSr);
|
||||
pipe.setParams(10.f, 1.17f, 1.f, 2800.f, 1.5f, 0.005f, 70.f, 350.f, 0.02f, false);
|
||||
pipe.setOutputGain(1.f);
|
||||
pipe.setTargetMode(true, 205.f);
|
||||
|
||||
std::vector<float> output(input.size() + 8192, 0.f);
|
||||
const int chunk = 480;
|
||||
for (size_t i = 0; i < input.size(); i += chunk) {
|
||||
pipe.process(input.data() + i, output.data() + i, (int)std::min((size_t)chunk, input.size() - i));
|
||||
}
|
||||
output.resize(input.size());
|
||||
|
||||
// 3) 测量(跳过开头 0.3s 的管线建立期,在 0.5~1.5s 稳态区测)
|
||||
const int m0 = (int)(0.5 * kSr);
|
||||
const int mN = (int)(1.0 * kSr);
|
||||
std::vector<float> segIn(input.begin() + m0, input.begin() + m0 + mN);
|
||||
std::vector<float> segOut(output.begin() + m0, output.begin() + m0 + mN);
|
||||
|
||||
const double f0Synth = 104.0; // 合成真值(100→108 缓升的中值,±3Hz 颤音)
|
||||
const double f0Out = measureF0(segOut.data(), mN, kSr);
|
||||
const double f1In = envelopePeak(segIn, 400, 1200, kSr);
|
||||
const double f1Out = envelopePeak(segOut, 400, 1400, kSr);
|
||||
const double f2In = envelopePeak(segIn, 900, 2000, kSr);
|
||||
const double f2Out = envelopePeak(segOut, 1000, 2400, kSr);
|
||||
const double hnrIn = hnrDb(segIn, f0Synth, kSr);
|
||||
const double hnrOut = hnrDb(segOut, f0Out > 20 ? f0Out : 205.0, kSr);
|
||||
|
||||
printf("\n%-16s %10s %10s %s\n", "指标", "输入(男声)", "输出", "判定");
|
||||
printf("%-14s %10.1f %10.1f %s\n", "基频f0(Hz)", f0Synth, f0Out,
|
||||
(f0Out > 190 && f0Out < 235) ? "[OK 锚定女声区]" : "[!! 偏离目标]");
|
||||
printf("%-14s %10.1f %10.1f 比值x%.2f (期望x1.17)\n", "F1包络(Hz)", f1In, f1Out, f1Out / f1In);
|
||||
printf("%-14s %10.1f %10.1f 比值x%.2f (期望x1.17)\n", "F2包络(Hz)", f2In, f2Out, f2Out / f2In);
|
||||
printf("%-14s %10.1f %10.1f %s\n", "谐波噪声比dB", hnrIn, hnrOut,
|
||||
hnrOut >= 8.0 ? "[OK 清晰]" : (hnrOut >= 5.0 ? "[一般]" : "[!! 模糊]"));
|
||||
printf("\n参考基频(合成真值):测量输入请以 %.0fHz 为准;上表 F 值为谱包络峰(±20Hz 栅格)。\n", f0Synth);
|
||||
printf("\nWAV 已写出: test\\in.wav(原始男声) test\\out.wav(变声后)——戴上耳机对比听\n");
|
||||
printf("注意:这两条是引擎裸输出,未经微信处理;微信端的降噪会进一步涂抹音质。\n");
|
||||
|
||||
writeWav("test/in.wav", input, kSr);
|
||||
writeWav("test/out.wav", output, kSr);
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,378 @@
|
||||
// pc-voice:PC 变声麦(男变女实时变声 → 虚拟声卡 → 微信/QQ 电脑版)
|
||||
//
|
||||
// 链路:物理麦克风 →[采集]→ DSP(PSOLA 变调+共振峰搬移)→[输出]→ VB-Cable Input
|
||||
// 微信/QQ 电脑版把「CABLE Output (VB-Audio Virtual Cable)」选作麦克风即生效
|
||||
//
|
||||
// 用法:
|
||||
// pc-voice.exe 交互模式(列设备→选择→运行)
|
||||
// pc-voice.exe --list 仅列音频设备
|
||||
// pc-voice.exe --line-out 线路输出模式(3.5mm 音频线连手机,方案一)
|
||||
// pc-voice.exe --in 名字片段 --out 名子片段 --config 配置路径
|
||||
//
|
||||
// 运行中快捷键:1 少女 / 2 御姐 / 3 萝莉 / 4 中性女 / B 旁路开关 / ESC 退出
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#define MINIAUDIO_IMPLEMENTATION
|
||||
#include "lib/miniaudio.h"
|
||||
|
||||
#include "config.h"
|
||||
#include "dsp_pipeline.h"
|
||||
|
||||
// 控制台输出统一入口:
|
||||
// 控制台 → WriteConsoleW 宽字符直写(免受代码页/GBK 影响,双击运行不乱码)
|
||||
// 重定向 → 保持 UTF-8 字节输出(便于日志与脚本采集)
|
||||
static void cprintf(const char* fmt, ...) {
|
||||
char buf[1024];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
|
||||
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
DWORD mode = 0;
|
||||
if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {
|
||||
wchar_t wbuf[1024];
|
||||
int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, 1024);
|
||||
if (wlen > 0) {
|
||||
DWORD written = 0;
|
||||
WriteConsoleW(h, wbuf, (DWORD)(wlen - 1), &written, NULL);
|
||||
}
|
||||
} else {
|
||||
fputs(buf, stdout);
|
||||
fflush(stdout);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 共享状态(采集线程 → 播放线程,SPSC 环) ----------
|
||||
static DspPipeline g_pipeline;
|
||||
static std::vector<float> g_ring;
|
||||
static std::atomic<long> g_w{0}, g_r{0};
|
||||
static std::atomic<int> g_underruns{0}, g_drops{0}, g_frames{0};
|
||||
static long g_ringCap = 8192;
|
||||
static long g_maxDepth = 960; // 环深上限 ≈ 20ms @48k
|
||||
|
||||
static void captureCallback(ma_device* dev, void* output, const void* input, ma_uint32 frameCount) {
|
||||
(void)dev;
|
||||
(void)output;
|
||||
if (frameCount > 4096) frameCount = 4096;
|
||||
|
||||
float tmp[4096];
|
||||
g_pipeline.process((const float*)input, tmp, (int)frameCount);
|
||||
|
||||
long w = g_w.load(std::memory_order_relaxed);
|
||||
long r = g_r.load(std::memory_order_acquire);
|
||||
for (ma_uint32 i = 0; i < frameCount; ++i) {
|
||||
if (w - r >= g_ringCap) break;
|
||||
g_ring[(size_t)(w & (g_ringCap - 1))] = tmp[i];
|
||||
++w;
|
||||
}
|
||||
g_w.store(w, std::memory_order_release);
|
||||
g_frames.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
static void playbackCallback(ma_device* dev, void* output, const void* input, ma_uint32 frameCount) {
|
||||
(void)dev;
|
||||
(void)input;
|
||||
float* dst = (float*)output;
|
||||
const ma_uint32 totalFrames = frameCount;
|
||||
if (frameCount > 4096) frameCount = 4096;
|
||||
|
||||
long w = g_w.load(std::memory_order_acquire);
|
||||
long r = g_r.load(std::memory_order_relaxed);
|
||||
|
||||
// 延迟控制器:积压超限丢最旧
|
||||
if (w - r > g_maxDepth) {
|
||||
r = w - g_maxDepth;
|
||||
g_drops.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
ma_uint32 got = 0;
|
||||
while (got < frameCount && r < w) {
|
||||
dst[got++] = g_ring[(size_t)(r & (g_ringCap - 1))];
|
||||
++r;
|
||||
}
|
||||
g_r.store(r, std::memory_order_release);
|
||||
for (ma_uint32 i = got; i < frameCount; ++i) dst[i] = 0.f;
|
||||
if (got < frameCount) g_underruns.fetch_add(1, std::memory_order_relaxed);
|
||||
|
||||
// 防御路径:帧数超界时清零尾部
|
||||
if (totalFrames > 4096) {
|
||||
memset((char*)output + 4096 * sizeof(float), 0, (size_t)(totalFrames - 4096) * sizeof(float));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 参数下发 ----------
|
||||
static VoiceCfg g_cfg;
|
||||
|
||||
static void applyParams() {
|
||||
g_pipeline.setParams(g_cfg.pitchSemitones, g_cfg.formantRatio, g_cfg.strength,
|
||||
g_cfg.eqFreqHz, g_cfg.eqGainDb, g_cfg.gateThreshold,
|
||||
g_cfg.f0MinHz, g_cfg.f0MaxHz, g_cfg.smoothing, g_cfg.bypass);
|
||||
g_pipeline.setOutputGain(g_cfg.outputGain);
|
||||
g_pipeline.setTargetMode(g_cfg.targetMode, g_cfg.targetF0Hz);
|
||||
}
|
||||
|
||||
static void applyPreset(int idx) {
|
||||
g_cfg.pitchSemitones = g_cfg.presets[idx][0];
|
||||
g_cfg.formantRatio = g_cfg.presets[idx][1];
|
||||
applyParams();
|
||||
cprintf("预设 → %s(+%.0f 半音, 共振峰 ×%.2f)\n",
|
||||
idx == 0 ? "少女" : idx == 1 ? "御姐" : idx == 2 ? "萝莉" : "中性女",
|
||||
(double)g_cfg.pitchSemitones, (double)g_cfg.formantRatio);
|
||||
}
|
||||
|
||||
// ---------- 设备工具 ----------
|
||||
struct DevicePick {
|
||||
std::string inName, outName, configPath;
|
||||
bool listOnly = false;
|
||||
bool allowSpeakers = false;
|
||||
};
|
||||
|
||||
static bool containsNoCase(const std::string& hay, const std::string& needle) {
|
||||
auto lower = [](std::string s) {
|
||||
for (auto& c : s) c = (char)tolower((unsigned char)c);
|
||||
return s;
|
||||
};
|
||||
return lower(hay).find(lower(needle)) != std::string::npos;
|
||||
}
|
||||
|
||||
static void printDevices(ma_context* ctx) {
|
||||
ma_device_info* pCapture = NULL;
|
||||
ma_uint32 nCapture = 0;
|
||||
ma_device_info* pPlayback = NULL;
|
||||
ma_uint32 nPlayback = 0;
|
||||
if (ma_context_get_devices(ctx, &pPlayback, &nPlayback, &pCapture, &nCapture) != MA_SUCCESS) {
|
||||
cprintf("设备枚举失败\n");
|
||||
return;
|
||||
}
|
||||
cprintf("==== 录音设备(--in)====\n");
|
||||
for (ma_uint32 i = 0; i < nCapture; ++i) {
|
||||
cprintf(" [%u] %s%s\n", i, pCapture[i].name,
|
||||
pCapture[i].isDefault ? " (默认)" : "");
|
||||
}
|
||||
cprintf("==== 播放设备(--out)====\n");
|
||||
for (ma_uint32 i = 0; i < nPlayback; ++i) {
|
||||
cprintf(" [%u] %s%s\n", i, pPlayback[i].name,
|
||||
pPlayback[i].isDefault ? " (默认)" : "");
|
||||
}
|
||||
}
|
||||
|
||||
static bool pickDevice(ma_context* ctx, ma_device_type type, const std::string& namePat,
|
||||
ma_device_id* outId, std::string& outName) {
|
||||
ma_device_info* pCapture = NULL;
|
||||
ma_uint32 nCapture = 0;
|
||||
ma_device_info* pPlayback = NULL;
|
||||
ma_uint32 nPlayback = 0;
|
||||
if (ma_context_get_devices(ctx, &pPlayback, &nPlayback, &pCapture, &nCapture) != MA_SUCCESS) {
|
||||
return false;
|
||||
}
|
||||
ma_device_info* list = (type == ma_device_type_capture) ? pCapture : pPlayback;
|
||||
ma_uint32 n = (type == ma_device_type_capture) ? nCapture : nPlayback;
|
||||
|
||||
// 采集端防自环:CABLE 是我们自己的输出回环;立体声混音收的是系统播放声,
|
||||
// 两者都不能当麦克风(否则 f0 恒 0 / 正反馈)
|
||||
auto isLoopback = [](const char* name) {
|
||||
return containsNoCase(name, "CABLE") || containsNoCase(name, "Mix") ||
|
||||
containsNoCase(name, "混音");
|
||||
};
|
||||
auto looksLikeMic = [](const char* name) {
|
||||
return containsNoCase(name, "Mic") || containsNoCase(name, "麦克风") ||
|
||||
containsNoCase(name, "Array") || containsNoCase(name, "Headset") ||
|
||||
containsNoCase(name, "耳麦");
|
||||
};
|
||||
|
||||
// 1) 名字模糊匹配
|
||||
if (!namePat.empty()) {
|
||||
for (ma_uint32 i = 0; i < n; ++i) {
|
||||
if (containsNoCase(list[i].name, namePat)) {
|
||||
*outId = list[i].id;
|
||||
outName = list[i].name;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
cprintf("警告:未找到包含「%s」的设备,改用默认设备\n", namePat.c_str());
|
||||
}
|
||||
// 2) 默认设备(采集端跳过回环设备)
|
||||
for (ma_uint32 i = 0; i < n; ++i) {
|
||||
if (list[i].isDefault) {
|
||||
if (type == ma_device_type_capture && isLoopback(list[i].name)) {
|
||||
cprintf("提示:跳过回环设备「%s」\n", list[i].name);
|
||||
continue;
|
||||
}
|
||||
*outId = list[i].id;
|
||||
outName = list[i].name;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// 3) 兜底一:优先选长得像麦克风的
|
||||
for (ma_uint32 i = 0; i < n; ++i) {
|
||||
if (type == ma_device_type_capture &&
|
||||
(isLoopback(list[i].name) || !looksLikeMic(list[i].name))) continue;
|
||||
*outId = list[i].id;
|
||||
outName = list[i].name;
|
||||
return true;
|
||||
}
|
||||
// 4) 兜底二:任意非回环设备
|
||||
for (ma_uint32 i = 0; i < n; ++i) {
|
||||
if (type == ma_device_type_capture && isLoopback(list[i].name)) continue;
|
||||
*outId = list[i].id;
|
||||
outName = list[i].name;
|
||||
return true;
|
||||
}
|
||||
return n > 0;
|
||||
}
|
||||
|
||||
// ---------- main ----------
|
||||
int main(int argc, char** argv) {
|
||||
cprintf("==== pc-voice 变声麦 v0.1(男变女实时变声)====\n");
|
||||
|
||||
DevicePick pick;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (!strcmp(argv[i], "--list")) pick.listOnly = true;
|
||||
else if (!strcmp(argv[i], "--line-out") || !strcmp(argv[i], "--allow-speakers")) pick.allowSpeakers = true;
|
||||
else if (!strcmp(argv[i], "--in") && i + 1 < argc) pick.inName = argv[++i];
|
||||
else if (!strcmp(argv[i], "--out") && i + 1 < argc) pick.outName = argv[++i];
|
||||
else if (!strcmp(argv[i], "--config") && i + 1 < argc) pick.configPath = argv[++i];
|
||||
}
|
||||
if (pick.configPath.empty()) pick.configPath = "voice_config.json";
|
||||
if (pick.outName.empty()) pick.outName = "CABLE Input"; // VB-Cable 默认输出端名
|
||||
|
||||
ma_context context;
|
||||
if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) {
|
||||
cprintf("音频子系统初始化失败\n");
|
||||
return 1;
|
||||
}
|
||||
if (pick.listOnly) {
|
||||
printDevices(&context);
|
||||
ma_context_uninit(&context);
|
||||
return 0;
|
||||
}
|
||||
|
||||
ma_device_id inId, outId;
|
||||
std::string inName, outName;
|
||||
if (!pickDevice(&context, ma_device_type_capture, pick.inName, &inId, inName) ||
|
||||
!pickDevice(&context, ma_device_type_playback, pick.outName, &outId, outName)) {
|
||||
cprintf("设备选择失败\n");
|
||||
ma_context_uninit(&context);
|
||||
return 1;
|
||||
}
|
||||
cprintf("输入: %s\n输出: %s\n", inName.c_str(), outName.c_str());
|
||||
|
||||
// 强校验:输出默认必须是虚拟声卡——直连扬声器会形成声反馈啸叫;
|
||||
// --line-out 明示"线已插到手机里"(方案一),此时物理输出不会回授
|
||||
if (!containsNoCase(outName, "CABLE") && !pick.allowSpeakers) {
|
||||
cprintf("\n错误:输出设备「%s」是扬声器,直连会啸叫。\n", outName.c_str());
|
||||
cprintf("方案一(音频线连手机):加 --line-out 启动(确认线已插入手机耳机孔)。\n");
|
||||
cprintf("方案二(微信/QQ 电脑版):安装 VB-Cable 后选「CABLE Input」(README 有步骤)。\n");
|
||||
ma_context_uninit(&context);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// 配置加载(缺失则用默认值,运行中每 2 秒热加载)
|
||||
bool hasCfg = loadConfig(pick.configPath, g_cfg);
|
||||
cprintf("配置: %s (%s)\n", pick.configPath.c_str(), hasCfg ? "已加载" : "缺失,用默认值");
|
||||
g_ring.assign((size_t)g_ringCap, 0.f); // 环形缓冲分配(音频回调前提)
|
||||
g_pipeline.setup(48000.f);
|
||||
applyParams();
|
||||
|
||||
// 设备配置:48kHz 单声道浮点,10ms 周期,低延迟档
|
||||
ma_device_config cfgIn = ma_device_config_init(ma_device_type_capture);
|
||||
cfgIn.capture.format = ma_format_f32;
|
||||
cfgIn.capture.channels = 1;
|
||||
cfgIn.capture.pDeviceID = &inId;
|
||||
cfgIn.sampleRate = 48000;
|
||||
cfgIn.periodSizeInMilliseconds = 10;
|
||||
cfgIn.performanceProfile = ma_performance_profile_low_latency;
|
||||
cfgIn.dataCallback = captureCallback;
|
||||
|
||||
ma_device_config cfgOut = ma_device_config_init(ma_device_type_playback);
|
||||
cfgOut.playback.format = ma_format_f32;
|
||||
cfgOut.playback.channels = 1;
|
||||
cfgOut.playback.pDeviceID = &outId;
|
||||
cfgOut.sampleRate = 48000;
|
||||
cfgOut.periodSizeInMilliseconds = 10;
|
||||
cfgOut.performanceProfile = ma_performance_profile_low_latency;
|
||||
cfgOut.dataCallback = playbackCallback;
|
||||
|
||||
ma_device devIn, devOut;
|
||||
if (ma_device_init(&context, &cfgIn, &devIn) != MA_SUCCESS ||
|
||||
ma_device_init(&context, &cfgOut, &devOut) != MA_SUCCESS) {
|
||||
cprintf("音频设备初始化失败(确认已安装 VB-Cable 且未被独占)\n");
|
||||
ma_context_uninit(&context);
|
||||
return 1;
|
||||
}
|
||||
if (ma_device_start(&devIn) != MA_SUCCESS || ma_device_start(&devOut) != MA_SUCCESS) {
|
||||
cprintf("音频设备启动失败\n");
|
||||
ma_context_uninit(&context);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (pick.allowSpeakers) {
|
||||
cprintf("运行中!方案一(线连手机):确认音频线已插入手机耳机孔,手机戴耳机通话。\n");
|
||||
} else {
|
||||
cprintf("运行中!方案二(电脑版):微信/QQ 把「CABLE Output (VB-Audio Virtual Cable)」选作麦克风。\n");
|
||||
}
|
||||
cprintf("快捷键:1 少女 / 2 御姐 / 3 萝莉 / 4 中性女 / B 旁路 / ESC 退出\n\n");
|
||||
|
||||
// 主循环:快捷键 + 统计 + 配置热加载
|
||||
long cfgMtime = 0;
|
||||
{
|
||||
WIN32_FILE_ATTRIBUTE_DATA fad;
|
||||
if (GetFileAttributesExA(pick.configPath.c_str(), GetFileExInfoStandard, &fad))
|
||||
cfgMtime = (long)fad.ftLastWriteTime.dwLowDateTime;
|
||||
}
|
||||
int tick = 0;
|
||||
for (;;) {
|
||||
Sleep(250);
|
||||
|
||||
// 快捷键(低 bit = 自上次调用以来按下过)
|
||||
if (GetAsyncKeyState('1') & 1) applyPreset(0);
|
||||
if (GetAsyncKeyState('2') & 1) applyPreset(1);
|
||||
if (GetAsyncKeyState('3') & 1) applyPreset(2);
|
||||
if (GetAsyncKeyState('4') & 1) applyPreset(3);
|
||||
if (GetAsyncKeyState('B') & 1) {
|
||||
g_cfg.bypass = !g_cfg.bypass;
|
||||
applyParams();
|
||||
cprintf("旁路 → %s\n", g_cfg.bypass ? "开(干声)" : "关(变声)");
|
||||
}
|
||||
if (GetAsyncKeyState(VK_ESCAPE) & 1) break;
|
||||
|
||||
// 配置热加载(每 2 秒)
|
||||
if ((++tick % 8) == 0) {
|
||||
WIN32_FILE_ATTRIBUTE_DATA fad;
|
||||
if (GetFileAttributesExA(pick.configPath.c_str(), GetFileExInfoStandard, &fad) &&
|
||||
(long)fad.ftLastWriteTime.dwLowDateTime != cfgMtime) {
|
||||
cfgMtime = (long)fad.ftLastWriteTime.dwLowDateTime;
|
||||
if (loadConfig(pick.configPath, g_cfg)) {
|
||||
applyParams();
|
||||
cprintf("配置已热更新\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 统计(每秒)
|
||||
if ((tick % 4) == 0) {
|
||||
long depth = g_w.load() - g_r.load();
|
||||
cprintf("f0=%.1fHz | 处理=%.2fms/帧 | 环深=%ld | 欠载=%d | 裁剪=%d | 端到端≈%.1fms | %s\n",
|
||||
(double)g_pipeline.currentF0(), (double)g_pipeline.avgProcMs(),
|
||||
depth, g_underruns.load(), g_drops.load(),
|
||||
(double)(depth + Psola::kLatencySamples + 2048) * 1000.0 / 48000.0,
|
||||
g_cfg.bypass ? "旁路" : "变声中");
|
||||
fflush(stdout);
|
||||
}
|
||||
}
|
||||
|
||||
ma_device_uninit(&devIn);
|
||||
ma_device_uninit(&devOut);
|
||||
ma_context_uninit(&context);
|
||||
cprintf("已退出。\n");
|
||||
return 0;
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"params": {
|
||||
"pitchSemitones": 10,
|
||||
"formantRatio": 1.17,
|
||||
"strength": 1,
|
||||
"eqFreqHz": 2800,
|
||||
"eqGainDb": 1.5,
|
||||
"gateThreshold": 0.005,
|
||||
"f0MinHz": 70,
|
||||
"f0MaxHz": 350,
|
||||
"smoothing": 0.02,
|
||||
"bypass": false,
|
||||
"outputGain": 1,
|
||||
"targetMode": true,
|
||||
"targetF0Hz": 205
|
||||
},
|
||||
"presets": [
|
||||
{ "name": "少女", "pitchSemitones": 11, "formantRatio": 1.22 },
|
||||
{ "name": "御姐", "pitchSemitones": 10, "formantRatio": 1.17 },
|
||||
{ "name": "萝莉", "pitchSemitones": 13, "formantRatio": 1.25 },
|
||||
{ "name": "中性女", "pitchSemitones": 8, "formantRatio": 1.15 }
|
||||
],
|
||||
"version": 1
|
||||
}
|
||||
Reference in New Issue
Block a user