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:
+29
@@ -0,0 +1,29 @@
|
||||
# ===== 本机工具链与临时目录(机器绑定,不入库)=====
|
||||
/.toolchain/
|
||||
/.tmp/
|
||||
|
||||
# ===== 任务指令文件(非项目源码)=====
|
||||
/info1.txt
|
||||
|
||||
# ===== Android 构建产物与缓存 =====
|
||||
realtime-voice/.gradle/
|
||||
realtime-voice/build/
|
||||
realtime-voice/app/build/
|
||||
realtime-voice/app/.cxx/
|
||||
realtime-voice/xposed/build/
|
||||
realtime-voice/xposed/.cxx/
|
||||
*.apk
|
||||
*.aab
|
||||
|
||||
# ===== 本机 SDK 路径配置 =====
|
||||
realtime-voice/local.properties
|
||||
|
||||
# ===== PC 端编译产物 =====
|
||||
pc-voice/*.exe
|
||||
|
||||
# ===== IDE / 系统杂项 =====
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'com.voicecraft.realtimevoice'
|
||||
compileSdk 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId 'com.voicecraft.realtimevoice'
|
||||
minSdk 24
|
||||
targetSdk 34
|
||||
versionCode 1
|
||||
versionName '0.1.0-m0'
|
||||
|
||||
ndk {
|
||||
// M0 只面向 arm64 真机(iQOO Neo3)
|
||||
abiFilters 'arm64-v8a'
|
||||
}
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
cppFlags '-O2'
|
||||
arguments '-DANDROID_STL=c++_shared'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
}
|
||||
debug {
|
||||
debuggable true
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path file('src/main/cpp/CMakeLists.txt')
|
||||
version '3.22.1'
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
// 通过 Prefab 引入 Google Oboe(低延迟音频库,Apache-2.0)
|
||||
prefab true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.google.oboe:oboe:1.9.3'
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- 实时变声:麦克风采集 -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<!-- 双机模式:前台服务保活 + 唤醒锁 -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<application
|
||||
android:label="@string/app_name"
|
||||
android:theme="@android:style/Theme.Material.Light"
|
||||
android:allowBackup="false">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="portrait">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".AudioFgService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="microphone" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,20 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
project(voiceengine LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# Google Oboe:低延迟音频采集/播放(Apache-2.0,经 Prefab 引入)
|
||||
find_package(oboe REQUIRED CONFIG)
|
||||
|
||||
add_library(voiceengine SHARED
|
||||
jni_bridge.cpp
|
||||
psola.cpp
|
||||
dsp_pipeline.cpp)
|
||||
|
||||
target_compile_options(voiceengine PRIVATE -O2 -Wall)
|
||||
|
||||
target_link_libraries(voiceengine
|
||||
oboe::oboe
|
||||
android
|
||||
log)
|
||||
@@ -0,0 +1,96 @@
|
||||
#pragma once
|
||||
|
||||
// RBJ 音频烹饪书双二阶滤波器(此处只用高频搁架,给女声加亮度)
|
||||
#include <cmath>
|
||||
|
||||
class HighShelf {
|
||||
public:
|
||||
void setup(float fs, float freq, float gainDb, float q = 0.707f) {
|
||||
const float A = std::pow(10.f, gainDb / 40.f);
|
||||
const float w0 = 2.f * 3.14159265f * freq / fs;
|
||||
const float cosw = std::cos(w0);
|
||||
const float sinw = std::sin(w0);
|
||||
const float alpha = sinw / (2.f * q);
|
||||
const float twoSqrtAAlpha = 2.f * std::sqrt(A) * alpha;
|
||||
|
||||
const float b0 = A * ((A + 1.f) + (A - 1.f) * cosw + twoSqrtAAlpha);
|
||||
const float b1 = -2.f * A * ((A - 1.f) + (A + 1.f) * cosw);
|
||||
const float b2 = A * ((A + 1.f) + (A - 1.f) * cosw - twoSqrtAAlpha);
|
||||
const float a0 = (A + 1.f) - (A - 1.f) * cosw + twoSqrtAAlpha;
|
||||
const float a1 = 2.f * ((A - 1.f) - (A + 1.f) * cosw);
|
||||
const float a2 = (A + 1.f) - (A - 1.f) * cosw - twoSqrtAAlpha;
|
||||
|
||||
b0_ = b0 / a0;
|
||||
b1_ = b1 / a0;
|
||||
b2_ = b2 / a0;
|
||||
a1_ = a1 / a0;
|
||||
a2_ = a2 / a0;
|
||||
reset();
|
||||
}
|
||||
|
||||
void reset() {
|
||||
x1_ = x2_ = y1_ = y2_ = 0.f;
|
||||
}
|
||||
|
||||
float processOne(float x) {
|
||||
const float y = b0_ * x + b1_ * x1_ + b2_ * x2_ - a1_ * y1_ - a2_ * y2_;
|
||||
x2_ = x1_;
|
||||
x1_ = x;
|
||||
y2_ = y1_;
|
||||
y1_ = y;
|
||||
return y;
|
||||
}
|
||||
|
||||
void process(float* buf, int n) {
|
||||
for (int i = 0; i < n; ++i) buf[i] = processOne(buf[i]);
|
||||
}
|
||||
|
||||
private:
|
||||
float b0_ = 1.f, b1_ = 0.f, b2_ = 0.f, a1_ = 0.f, a2_ = 0.f;
|
||||
float x1_ = 0.f, x2_ = 0.f, y1_ = 0.f, y2_ = 0.f;
|
||||
};
|
||||
|
||||
// RBJ 高通滤波器:掐掉低频轰鸣/电流声(必须在变调前用,否则噪声被搬移成可听噪声)
|
||||
class HighPass {
|
||||
public:
|
||||
void setup(float fs, float freq, float q = 0.707f) {
|
||||
const float w0 = 2.f * 3.14159265f * freq / fs;
|
||||
const float cosw = std::cos(w0);
|
||||
const float sinw = std::sin(w0);
|
||||
const float alpha = sinw / (2.f * q);
|
||||
|
||||
const float b0 = (1.f + cosw) / 2.f;
|
||||
const float b1 = -(1.f + cosw);
|
||||
const float b2 = (1.f + cosw) / 2.f;
|
||||
const float a0 = 1.f + alpha;
|
||||
const float a1 = -2.f * cosw;
|
||||
const float a2 = 1.f - alpha;
|
||||
|
||||
b0_ = b0 / a0;
|
||||
b1_ = b1 / a0;
|
||||
b2_ = b2 / a0;
|
||||
a1_ = a1 / a0;
|
||||
a2_ = a2 / a0;
|
||||
reset();
|
||||
}
|
||||
|
||||
void reset() {
|
||||
x1_ = x2_ = y1_ = y2_ = 0.f;
|
||||
}
|
||||
|
||||
void process(float* buf, int n) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const float x = buf[i];
|
||||
const float y = b0_ * x + b1_ * x1_ + b2_ * x2_ - a1_ * y1_ - a2_ * y2_;
|
||||
x2_ = x1_;
|
||||
x1_ = x;
|
||||
y2_ = y1_;
|
||||
y1_ = y;
|
||||
buf[i] = y;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
float b0_ = 1.f, b1_ = 0.f, b2_ = 0.f, a1_ = 0.f, a2_ = 0.f;
|
||||
float x1_ = 0.f, x2_ = 0.f, y1_ = 0.f, y2_ = 0.f;
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
#include "dsp_pipeline.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
|
||||
void DspPipeline::setup(float sampleRate) {
|
||||
fs_ = sampleRate;
|
||||
yin_.setup(fs_, kYinWin);
|
||||
yin_.setRange(65.f, 500.f);
|
||||
shelf_.setup(fs_, 3000.f, 3.f, 0.707f);
|
||||
hp_.setup(fs_, 85.f, 0.707f); // 85Hz 高通:掐低频轰鸣/电流声
|
||||
psola_.setup(fs_);
|
||||
yinHist_.assign(kYinWin, 0.f);
|
||||
yinWinScratch_.assign(kYinWin, 0.f);
|
||||
hpBuf_.reserve(4096);
|
||||
delayBuf_.assign(4096, 0.f);
|
||||
reset();
|
||||
}
|
||||
|
||||
void DspPipeline::reset() {
|
||||
yinHistFill_ = 0;
|
||||
sinceYin_ = 0;
|
||||
lastF0_ = 120.f;
|
||||
f0Hist_[0] = f0Hist_[1] = f0Hist_[2] = 0.f;
|
||||
f0HistIdx_ = 0;
|
||||
unvoicedCount_ = 0;
|
||||
delayWrite_ = 4096;
|
||||
delaySmoothed_ = (float)Psola::kLatencySamples;
|
||||
gateGain_ = 0.f;
|
||||
std::fill(yinHist_.begin(), yinHist_.end(), 0.f);
|
||||
std::fill(delayBuf_.begin(), delayBuf_.end(), 0.f);
|
||||
shelf_.reset();
|
||||
hp_.reset();
|
||||
psola_.reset();
|
||||
refreshTargets();
|
||||
}
|
||||
|
||||
void DspPipeline::setParams(float pitchSemis, float formantRatio, float strength,
|
||||
float eqFreqHz, float eqGainDb, float gateThreshold,
|
||||
float f0MinHz, float f0MaxHz, float smoothing, bool bypass) {
|
||||
// 只写原子量;PSOLA/EQ 状态一律在音频线程 refreshTargets() 中更新(线程安全)
|
||||
pitchSemis_.store(pitchSemis, std::memory_order_relaxed);
|
||||
formantRatio_.store(formantRatio, std::memory_order_relaxed);
|
||||
strength_.store(std::max(0.f, std::min(1.f, strength)), std::memory_order_relaxed);
|
||||
eqFreqHz_.store(std::max(200.f, std::min(12000.f, eqFreqHz)), std::memory_order_relaxed);
|
||||
eqGainDb_.store(std::max(0.f, std::min(12.f, eqGainDb)), std::memory_order_relaxed);
|
||||
gateThreshold_.store(std::max(0.f, std::min(0.05f, gateThreshold)), std::memory_order_relaxed);
|
||||
f0MinHz_.store(std::max(40.f, std::min(200.f, f0MinHz)), std::memory_order_relaxed);
|
||||
f0MaxHz_.store(std::max(300.f, std::min(800.f, f0MaxHz)), std::memory_order_relaxed);
|
||||
smoothing_.store(std::max(0.001f, std::min(0.5f, smoothing)), std::memory_order_relaxed);
|
||||
bypass_.store(bypass, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void DspPipeline::setOutputGain(float gain) {
|
||||
outputGain_.store(std::max(0.1f, std::min(2.f, gain)), std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void DspPipeline::setTargetMode(bool enabled, float targetF0Hz) {
|
||||
targetMode_.store(enabled, std::memory_order_relaxed);
|
||||
targetF0Hz_.store(std::max(120.f, std::min(320.f, targetF0Hz)), std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void DspPipeline::refreshTargets() {
|
||||
const float s = strength_.load(std::memory_order_relaxed);
|
||||
const float semis = pitchSemis_.load(std::memory_order_relaxed);
|
||||
const float formant = formantRatio_.load(std::memory_order_relaxed);
|
||||
|
||||
// 音高倍率:
|
||||
// 比例模式 = 2^(半音/12)
|
||||
// 目标模式 = 目标f0 ÷ 实时输入f0(输出锚定女声区,深沉嗓音自动多补)
|
||||
float rawRatio;
|
||||
if (targetMode_.load(std::memory_order_relaxed)) {
|
||||
const float tgt = targetF0Hz_.load(std::memory_order_relaxed);
|
||||
rawRatio = (lastF0_ > 1.f) ? std::max(0.5f, std::min(4.f, tgt / lastF0_)) : 1.f;
|
||||
} else {
|
||||
rawRatio = std::pow(2.f, semis / 12.f);
|
||||
}
|
||||
// 强度混合:0 = 干声参数,1 = 全效果
|
||||
const float ratio = 1.f + (rawRatio - 1.f) * s;
|
||||
const float effFormant = 1.f + (formant - 1.f) * s;
|
||||
|
||||
psola_.setRatios(ratio, effFormant);
|
||||
psola_.setSmoothing(smoothing_.load(std::memory_order_relaxed));
|
||||
psola_.setPeriodTargets(fs_ / lastF0_, (fs_ / lastF0_) / ratio);
|
||||
|
||||
// 基频检测范围变化时才重配(便宜,但避免无谓调用)
|
||||
const float f0Min = f0MinHz_.load(std::memory_order_relaxed);
|
||||
const float f0Max = f0MaxHz_.load(std::memory_order_relaxed);
|
||||
if (f0Min != lastF0Min_ || f0Max != lastF0Max_) {
|
||||
yin_.setRange(f0Min, f0Max);
|
||||
lastF0Min_ = f0Min;
|
||||
lastF0Max_ = f0Max;
|
||||
}
|
||||
|
||||
// EQ 参数变化时才重建滤波器(重建会清状态,每帧做会产生爆音)
|
||||
const float eqF = eqFreqHz_.load(std::memory_order_relaxed);
|
||||
const float eqG = eqGainDb_.load(std::memory_order_relaxed);
|
||||
if (eqF != lastEqFreq_ || eqG != lastEqGain_) {
|
||||
shelf_.setup(fs_, eqF, eqG, 0.707f);
|
||||
lastEqFreq_ = eqF;
|
||||
lastEqGain_ = eqG;
|
||||
}
|
||||
}
|
||||
|
||||
void DspPipeline::process(const float* in, float* out, int n) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
|
||||
// 参数目标在音频线程内刷新(与 PSOLA 状态单线程接触,避免竞态)
|
||||
refreshTargets();
|
||||
|
||||
// --- 基频检测:环形历史 + 每 ~20ms 组装连续窗口检测一次 ---
|
||||
for (int i = 0; i < n; ++i) {
|
||||
yinHist_[(size_t)yinHistFill_] = in[i];
|
||||
yinHistFill_ = (yinHistFill_ + 1) % kYinWin;
|
||||
}
|
||||
sinceYin_ += n;
|
||||
if (sinceYin_ >= 960) { // ~20ms @48k
|
||||
sinceYin_ = 0;
|
||||
// 组装连续窗口(旧→新)再检测,避免环形回绕读到错序数据
|
||||
for (int i = 0; i < kYinWin; ++i) {
|
||||
yinWinScratch_[(size_t)i] = yinHist_[(size_t)((yinHistFill_ + i) % kYinWin)];
|
||||
}
|
||||
float f0 = yin_.detect(yinWinScratch_.data());
|
||||
if (f0 > 0.f) {
|
||||
unvoicedCount_ = 0;
|
||||
// 八度纠错:YIN 在中低男声+噪声下常把 f0 认成 2 倍/0.5 倍(八度错误),
|
||||
// 会让输出音调跳变(听感=忽高忽低 + 毛刺)。对照历史值纠回。
|
||||
if (lastF0_ > 0.f) {
|
||||
const float r = f0 / lastF0_;
|
||||
if (r > 1.7f && r < 2.4f) f0 *= 0.5f;
|
||||
else if (r > 0.4f && r < 0.6f) f0 *= 2.f;
|
||||
}
|
||||
// 3 帧中值滤波:剔除偶发野值
|
||||
f0Hist_[f0HistIdx_] = f0;
|
||||
f0HistIdx_ = (f0HistIdx_ + 1) % 3;
|
||||
float a = f0Hist_[0], b = f0Hist_[1], c = f0Hist_[2];
|
||||
if (a > b) std::swap(a, b);
|
||||
if (b > c) std::swap(b, c);
|
||||
if (a > b) std::swap(a, b);
|
||||
const float med = (b > 0.f) ? b : f0;
|
||||
|
||||
// 大跳变限速(单帧最多 ±15%),防音调台阶感;
|
||||
// 恒朝目标收敛(两个方向都是差值 × 0.15)
|
||||
if (lastF0_ > 0.f && std::fabs(med - lastF0_) / lastF0_ > 0.15f) {
|
||||
lastF0_ += (med - lastF0_) * 0.15f;
|
||||
} else {
|
||||
lastF0_ = med;
|
||||
}
|
||||
} else {
|
||||
// 清音计数:长时间清音后清空历史,防句首中值残留旧音高
|
||||
if (++unvoicedCount_ > 25) {
|
||||
f0Hist_[0] = f0Hist_[1] = f0Hist_[2] = 0.f;
|
||||
}
|
||||
}
|
||||
// 显示实际使用的稳定值(而非原始检测值),与听感一致
|
||||
f0Display_.store(f0 > 0.f ? lastF0_ : 0.f, std::memory_order_relaxed);
|
||||
refreshTargets();
|
||||
}
|
||||
|
||||
// --- 旁路 / 变声 ---
|
||||
const bool bypass = bypass_.load(std::memory_order_relaxed);
|
||||
if (bypass) {
|
||||
// 旁路走分数延迟线:延迟追踪湿声实际延迟(kLatency + 当前粒周期),
|
||||
// 平滑过渡避免 A/B 切换时的梳状失真与爆音
|
||||
const float targetDelay = (float)Psola::kLatencySamples + psola_.currentTOut();
|
||||
delaySmoothed_ += (targetDelay - delaySmoothed_) * 0.002f;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
delayBuf_[(size_t)(delayWrite_ & 4095)] = in[i];
|
||||
const float readPos = (float)delayWrite_ - delaySmoothed_;
|
||||
const long i0 = (long)std::floor(readPos);
|
||||
const float frac = readPos - (float)i0;
|
||||
const float s0 = delayBuf_[(size_t)(i0 & 4095)];
|
||||
const float s1 = delayBuf_[(size_t)((i0 + 1) & 4095)];
|
||||
out[i] = s0 + (s1 - s0) * frac;
|
||||
++delayWrite_;
|
||||
}
|
||||
} else {
|
||||
// 高通滤波后的输入进 PSOLA(低频噪声在变调前滤除,防止被搬移成可听噪声)
|
||||
hpBuf_.resize((size_t)n);
|
||||
for (int i = 0; i < n; ++i) hpBuf_[(size_t)i] = in[i];
|
||||
hp_.process(hpBuf_.data(), n);
|
||||
psola_.process(hpBuf_.data(), out, n);
|
||||
|
||||
// 高频亮度(女声)
|
||||
shelf_.process(out, n);
|
||||
}
|
||||
|
||||
// --- 噪声扩展器(连续压低底噪,替代硬开关防泵动):快放慢收 ---
|
||||
float rms = 0.f;
|
||||
for (int i = 0; i < n; ++i) rms += in[i] * in[i];
|
||||
rms = std::sqrt(rms / (float)std::max(1, n));
|
||||
const float gt = gateThreshold_.load(std::memory_order_relaxed);
|
||||
const float targetGate = gt <= 0.f ? 1.f : std::min(1.f, rms / gt);
|
||||
const float gateCoef = targetGate > gateGain_ ? 0.3f : 0.005f;
|
||||
gateGain_ += (targetGate - gateGain_) * gateCoef;
|
||||
const float outGain = outputGain_.load(std::memory_order_relaxed);
|
||||
// 软饱和替代硬削波:0.7 以下线性,以上 tanh 软拐点(硬限幅是"刺啦"声的主源)
|
||||
auto softClip = [](float v) {
|
||||
const float a = std::fabs(v);
|
||||
if (a <= 0.7f) return v;
|
||||
const float s = v > 0.f ? 1.f : -1.f;
|
||||
return s * (0.7f + 0.3f * std::tanh((a - 0.7f) / 0.3f));
|
||||
};
|
||||
if (!bypass) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
out[i] = softClip(out[i] * gateGain_ * outGain);
|
||||
}
|
||||
} else {
|
||||
// 旁路同样应用输出增益(A/B 对比时电平公平)
|
||||
for (int i = 0; i < n; ++i) {
|
||||
out[i] = softClip(out[i] * outGain);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 统计 ---
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
const float ms = std::chrono::duration<float, std::milli>(t1 - t0).count();
|
||||
procMs_.store(ms, std::memory_order_relaxed);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
// DSP 管线:门限 → 基频检测 → PSOLA 变调/共振峰搬移 → 高频亮度 → 软限幅
|
||||
// 线程模型:仅音频回调线程调用 process();setParams() 可任意线程调用。
|
||||
#include <atomic>
|
||||
|
||||
#include "yin.h"
|
||||
#include "biquad.h"
|
||||
#include "psola.h"
|
||||
|
||||
class DspPipeline {
|
||||
public:
|
||||
void setup(float sampleRate);
|
||||
void reset();
|
||||
|
||||
// 全参数接口(与 voice_config.json 一一对应,参数说明见 VoiceConfig.java)
|
||||
void setParams(float pitchSemis, float formantRatio, float strength,
|
||||
float eqFreqHz, float eqGainDb, float gateThreshold,
|
||||
float f0MinHz, float f0MaxHz, float smoothing, bool bypass);
|
||||
|
||||
// 输出增益(0.1~2.0):双机线路输出时匹配目标手机麦克风电平
|
||||
void setOutputGain(float gain);
|
||||
|
||||
// 目标音高模式:输出 f0 锚定 targetF0Hz(深沉嗓音自动多补),关闭时按半音比例变调
|
||||
void setTargetMode(bool enabled, float targetF0Hz);
|
||||
|
||||
// 定长块处理(in/out 不可别名)
|
||||
void process(const float* in, float* out, int n);
|
||||
|
||||
// 统计
|
||||
float currentF0() const { return f0Display_.load(std::memory_order_relaxed); }
|
||||
float avgProcMs() const { return procMs_.load(std::memory_order_relaxed); }
|
||||
int psolaUnderruns() const { return psola_.underruns(); }
|
||||
|
||||
private:
|
||||
void refreshTargets();
|
||||
|
||||
float fs_ = 48000.f;
|
||||
|
||||
std::atomic<float> pitchSemis_{9.f};
|
||||
std::atomic<float> formantRatio_{1.20f};
|
||||
std::atomic<float> strength_{1.f};
|
||||
std::atomic<float> eqFreqHz_{3000.f};
|
||||
std::atomic<float> eqGainDb_{3.f};
|
||||
std::atomic<float> gateThreshold_{0.006f};
|
||||
std::atomic<float> f0MinHz_{65.f};
|
||||
std::atomic<float> f0MaxHz_{500.f};
|
||||
std::atomic<float> smoothing_{0.05f};
|
||||
std::atomic<float> outputGain_{1.f};
|
||||
std::atomic<bool> targetMode_{false};
|
||||
std::atomic<float> targetF0Hz_{205.f};
|
||||
std::atomic<bool> bypass_{false};
|
||||
|
||||
// EQ 重配检测(避免每帧重建滤波器产生爆音)
|
||||
float lastEqFreq_ = -1.f;
|
||||
float lastEqGain_ = -1.f;
|
||||
float lastF0Min_ = -1.f;
|
||||
float lastF0Max_ = -1.f;
|
||||
|
||||
Yin yin_;
|
||||
HighShelf shelf_;
|
||||
HighPass hp_;
|
||||
Psola psola_;
|
||||
|
||||
static constexpr int kYinWin = 1024;
|
||||
std::vector<float> yinHist_;
|
||||
std::vector<float> yinWinScratch_;
|
||||
std::vector<float> hpBuf_; // 高通后的湿声输入(变调前滤除低频噪声)
|
||||
int yinHistFill_ = 0;
|
||||
int sinceYin_ = 0;
|
||||
float lastF0_ = 120.f;
|
||||
float f0Hist_[3] = {0.f, 0.f, 0.f}; // 3 帧中值稳定用
|
||||
int f0HistIdx_ = 0;
|
||||
int unvoicedCount_ = 0;
|
||||
|
||||
std::vector<float> delayBuf_; // 旁路分数延迟线(追踪湿声延迟,线性插值)
|
||||
long delayWrite_ = 4096;
|
||||
float delaySmoothed_ = (float)Psola::kLatencySamples;
|
||||
|
||||
float gateGain_ = 0.f;
|
||||
|
||||
std::atomic<float> f0Display_{0.f};
|
||||
std::atomic<float> procMs_{0.f};
|
||||
};
|
||||
@@ -0,0 +1,342 @@
|
||||
// JNI 桥 + Oboe 低延迟双工音频
|
||||
//
|
||||
// 线程模型:
|
||||
// 输入回调线程:采集 → DspPipeline::process → 推入输出环
|
||||
// 输出回调线程:弹出输出环 → 播放(欠载补零计数)
|
||||
// Java 线程: setParams / setOutputGain / getStats(仅触碰原子量)
|
||||
// 错误自愈线程: 音频流被系统关闭(来电/焦点抢占)后自动重启
|
||||
//
|
||||
// 注意:一律使用 Shared 共享流(vivo 等厂商 HAL 对独占 MMAP 双流有缺陷,
|
||||
// 曾导致 audioserver 卡死系统崩溃,见 M0 复盘)
|
||||
|
||||
#include <jni.h>
|
||||
#include <oboe/Oboe.h>
|
||||
#include <android/log.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "dsp_pipeline.h"
|
||||
|
||||
#define LOG_TAG "VoiceEngine"
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRingCap = 8192; // 2 的幂
|
||||
|
||||
class AudioEngine : public oboe::AudioStreamDataCallback,
|
||||
public oboe::AudioStreamErrorCallback {
|
||||
public:
|
||||
static AudioEngine& instance() {
|
||||
static AudioEngine e;
|
||||
return e;
|
||||
}
|
||||
|
||||
bool start(int preferredRate) {
|
||||
std::lock_guard<std::mutex> lk(mutex_);
|
||||
return startLocked(preferredRate);
|
||||
}
|
||||
|
||||
void stop() {
|
||||
std::lock_guard<std::mutex> lk(mutex_);
|
||||
stopLocked();
|
||||
}
|
||||
|
||||
void setParams(float pitchSemis, float formant, float strength,
|
||||
float eqFreqHz, float eqGainDb, float gateThreshold,
|
||||
float f0MinHz, float f0MaxHz, float smoothing, bool bypass) {
|
||||
pipeline_.setParams(pitchSemis, formant, strength,
|
||||
eqFreqHz, eqGainDb, gateThreshold,
|
||||
f0MinHz, f0MaxHz, smoothing, bypass);
|
||||
}
|
||||
|
||||
void setOutputGain(float gain) {
|
||||
pipeline_.setOutputGain(gain);
|
||||
}
|
||||
|
||||
void setTargetMode(bool enabled, float targetF0Hz) {
|
||||
pipeline_.setTargetMode(enabled, targetF0Hz);
|
||||
}
|
||||
|
||||
std::string stats() {
|
||||
char buf[256];
|
||||
const long produced = ringWrite_.load();
|
||||
const long consumed = ringRead_.load();
|
||||
snprintf(buf, sizeof(buf),
|
||||
"采样率=%d | 回调=%d | 处理=%.2fms/帧 | f0=%.1fHz | 环深=%ld | 欠载=%d | 裁剪=%d | 端到端≈%.1fms",
|
||||
sampleRate_,
|
||||
framesIn_.load(std::memory_order_relaxed),
|
||||
pipeline_.avgProcMs(),
|
||||
pipeline_.currentF0(),
|
||||
produced - consumed,
|
||||
outUnderruns_.load(),
|
||||
ringLatencyDrops_.load(),
|
||||
((float)(produced - consumed) + (float)Psola::kLatencySamples + 384.f)
|
||||
* 1000.f / (float)std::max(1, sampleRate_));
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// ---- Oboe 数据回调 ----
|
||||
oboe::DataCallbackResult onAudioReady(oboe::AudioStream* stream,
|
||||
void* audioData,
|
||||
int32_t numFrames) override {
|
||||
if (stream == inStream_.get()) {
|
||||
onInput(audioData, numFrames);
|
||||
} else {
|
||||
onOutput(audioData, numFrames);
|
||||
}
|
||||
return oboe::DataCallbackResult::Continue;
|
||||
}
|
||||
|
||||
// ---- Oboe 错误回调:来电/音频焦点抢占导致流关闭时自愈重启 ----
|
||||
void onErrorAfterClose(oboe::AudioStream* /*stream*/, oboe::Result error) override {
|
||||
LOGE("音频流异常关闭(err=%d),准备自愈重启", (int)error);
|
||||
if (!running_) return;
|
||||
std::thread([this]() {
|
||||
std::lock_guard<std::mutex> lk(mutex_);
|
||||
if (!running_) return;
|
||||
LOGI("自愈:重启音频流");
|
||||
stopLocked();
|
||||
if (startLocked(lastPreferredRate_)) {
|
||||
LOGI("自愈成功");
|
||||
} else {
|
||||
LOGE("自愈失败,等待用户手动重启");
|
||||
}
|
||||
}).detach();
|
||||
}
|
||||
|
||||
private:
|
||||
bool startLocked(int preferredRate) {
|
||||
if (running_) return true;
|
||||
lastPreferredRate_ = preferredRate;
|
||||
|
||||
ring_.assign(kRingCap, 0.f);
|
||||
ringRead_.store(0);
|
||||
ringWrite_.store(0);
|
||||
outUnderruns_.store(0);
|
||||
ringLatencyDrops_.store(0);
|
||||
framesIn_.store(0);
|
||||
|
||||
// --- 输入流:共享模式(厂商兼容性,见文件头注释)---
|
||||
oboe::AudioStreamBuilder inb;
|
||||
inb.setDirection(oboe::Direction::Input)
|
||||
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
|
||||
->setSharingMode(oboe::SharingMode::Shared)
|
||||
->setFormat(oboe::AudioFormat::Float)
|
||||
->setChannelCount(1)
|
||||
->setDataCallback(this)
|
||||
->setErrorCallback(this);
|
||||
if (preferredRate > 0) inb.setSampleRate(preferredRate);
|
||||
|
||||
if (inb.openStream(inStream_) != oboe::Result::OK) {
|
||||
LOGE("输入流打开失败");
|
||||
return false;
|
||||
}
|
||||
|
||||
const int rate = inStream_->getSampleRate();
|
||||
inIsFloat_ = (inStream_->getFormat() == oboe::AudioFormat::Float);
|
||||
|
||||
// --- 输出流:与输入同采样率,同为共享模式 ---
|
||||
oboe::AudioStreamBuilder outb;
|
||||
outb.setDirection(oboe::Direction::Output)
|
||||
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
|
||||
->setSharingMode(oboe::SharingMode::Shared)
|
||||
->setFormat(oboe::AudioFormat::Float)
|
||||
->setChannelCount(1)
|
||||
->setSampleRate(rate)
|
||||
->setDataCallback(this)
|
||||
->setErrorCallback(this);
|
||||
if (outb.openStream(outStream_) != oboe::Result::OK) {
|
||||
LOGE("输出流打开失败");
|
||||
inStream_->close();
|
||||
inStream_.reset();
|
||||
return false;
|
||||
}
|
||||
outIsFloat_ = (outStream_->getFormat() == oboe::AudioFormat::Float);
|
||||
|
||||
sampleRate_ = rate;
|
||||
pipeline_.setup((float)rate);
|
||||
|
||||
inStream_->requestStart();
|
||||
outStream_->requestStart();
|
||||
running_ = true;
|
||||
LOGI("音频已启动 sr=%d in=%s out=%s bufs=%d/%d",
|
||||
rate,
|
||||
inIsFloat_ ? "F32" : "I16",
|
||||
outIsFloat_ ? "F32" : "I16",
|
||||
inStream_->getBufferSizeInFrames(),
|
||||
outStream_->getBufferSizeInFrames());
|
||||
return true;
|
||||
}
|
||||
|
||||
void stopLocked() {
|
||||
if (!running_ && !inStream_ && !outStream_) return;
|
||||
running_ = false;
|
||||
if (inStream_) {
|
||||
inStream_->stop();
|
||||
inStream_->close();
|
||||
inStream_.reset();
|
||||
}
|
||||
if (outStream_) {
|
||||
outStream_->stop();
|
||||
outStream_->close();
|
||||
outStream_.reset();
|
||||
}
|
||||
LOGI("音频已停止");
|
||||
}
|
||||
|
||||
void onInput(void* audioData, int32_t numFrames) {
|
||||
if (numFrames > kMaxFrames) numFrames = kMaxFrames;
|
||||
|
||||
// 格式转换 → 浮点
|
||||
if (inIsFloat_) {
|
||||
const float* src = static_cast<const float*>(audioData);
|
||||
for (int i = 0; i < numFrames; ++i) inBuf_[i] = src[i];
|
||||
} else {
|
||||
const int16_t* src = static_cast<const int16_t*>(audioData);
|
||||
for (int i = 0; i < numFrames; ++i) inBuf_[i] = (float)src[i] / 32768.f;
|
||||
}
|
||||
|
||||
pipeline_.process(inBuf_, procBuf_, numFrames);
|
||||
framesIn_.fetch_add(1, std::memory_order_relaxed);
|
||||
|
||||
// 推入输出环(满则丢新帧,保证实时)
|
||||
long w = ringWrite_.load(std::memory_order_relaxed);
|
||||
long r = ringRead_.load(std::memory_order_acquire);
|
||||
for (int i = 0; i < numFrames; ++i) {
|
||||
if (w - r >= kRingCap) break;
|
||||
ring_[(size_t)(w & (kRingCap - 1))] = procBuf_[i];
|
||||
++w;
|
||||
}
|
||||
ringWrite_.store(w, std::memory_order_release);
|
||||
}
|
||||
|
||||
void onOutput(void* audioData, int32_t numFrames) {
|
||||
const int32_t totalFrames = numFrames;
|
||||
if (numFrames > kMaxFrames) numFrames = kMaxFrames;
|
||||
|
||||
long w = ringWrite_.load(std::memory_order_acquire);
|
||||
long r = ringRead_.load(std::memory_order_relaxed);
|
||||
|
||||
// 延迟控制器:积压超限(如启动时序抖动)时丢弃最旧样本
|
||||
if (w - r > kMaxRingDepth) {
|
||||
r = w - kMaxRingDepth;
|
||||
ringLatencyDrops_.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int got = 0;
|
||||
while (got < numFrames && r < w) {
|
||||
outBuf_[got++] = ring_[(size_t)(r & (kRingCap - 1))];
|
||||
++r;
|
||||
}
|
||||
ringRead_.store(r, std::memory_order_release);
|
||||
if (got < numFrames) {
|
||||
outUnderruns_.fetch_add(1, std::memory_order_relaxed);
|
||||
for (int i = got; i < numFrames; ++i) outBuf_[i] = 0.f;
|
||||
}
|
||||
|
||||
if (outIsFloat_) {
|
||||
float* dst = static_cast<float*>(audioData);
|
||||
for (int i = 0; i < numFrames; ++i) dst[i] = outBuf_[i];
|
||||
} else {
|
||||
int16_t* dst = static_cast<int16_t*>(audioData);
|
||||
for (int i = 0; i < numFrames; ++i) {
|
||||
float v = outBuf_[i] * 32767.f;
|
||||
if (v > 32767.f) v = 32767.f;
|
||||
if (v < -32768.f) v = -32768.f;
|
||||
dst[i] = (int16_t)v;
|
||||
}
|
||||
}
|
||||
// 防御路径:帧数超界时清零尾部(float=0 与 int16=0 同为全零字节)
|
||||
if (totalFrames > kMaxFrames) {
|
||||
const size_t sampleBytes = outIsFloat_ ? 4 : 2;
|
||||
memset(static_cast<char*>(audioData) + (size_t)kMaxFrames * sampleBytes, 0,
|
||||
(size_t)(totalFrames - kMaxFrames) * sampleBytes);
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr int kMaxFrames = 4096;
|
||||
// 输出环深度上限 ≈ 800 样本(16.7ms @48k)
|
||||
static constexpr long kMaxRingDepth = 800;
|
||||
|
||||
std::mutex mutex_;
|
||||
std::shared_ptr<oboe::AudioStream> inStream_;
|
||||
std::shared_ptr<oboe::AudioStream> outStream_;
|
||||
std::atomic<bool> running_{false};
|
||||
int lastPreferredRate_ = 0;
|
||||
int sampleRate_ = 48000;
|
||||
bool inIsFloat_ = true, outIsFloat_ = true;
|
||||
|
||||
DspPipeline pipeline_;
|
||||
|
||||
std::vector<float> ring_;
|
||||
std::atomic<long> ringRead_{0};
|
||||
std::atomic<long> ringWrite_{0};
|
||||
std::atomic<int> outUnderruns_{0};
|
||||
std::atomic<int> ringLatencyDrops_{0};
|
||||
std::atomic<int> framesIn_{0};
|
||||
|
||||
float inBuf_[kMaxFrames];
|
||||
float procBuf_[kMaxFrames];
|
||||
float outBuf_[kMaxFrames];
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---------------- JNI ----------------
|
||||
extern "C" {
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_voicecraft_realtimevoice_VoiceEngine_nativeStart(JNIEnv*, jobject, jint preferredRate) {
|
||||
return AudioEngine::instance().start((int)preferredRate) ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_realtimevoice_VoiceEngine_nativeStop(JNIEnv*, jobject) {
|
||||
AudioEngine::instance().stop();
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_realtimevoice_VoiceEngine_nativeSetParams(JNIEnv*, jobject,
|
||||
jfloat pitchSemis,
|
||||
jfloat formant,
|
||||
jfloat strength,
|
||||
jfloat eqFreqHz,
|
||||
jfloat eqGainDb,
|
||||
jfloat gateThreshold,
|
||||
jfloat f0MinHz,
|
||||
jfloat f0MaxHz,
|
||||
jfloat smoothing,
|
||||
jboolean bypass) {
|
||||
AudioEngine::instance().setParams(pitchSemis, formant, strength,
|
||||
eqFreqHz, eqGainDb, gateThreshold,
|
||||
f0MinHz, f0MaxHz, smoothing, bypass == JNI_TRUE);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_realtimevoice_VoiceEngine_nativeSetOutputGain(JNIEnv*, jobject,
|
||||
jfloat gain) {
|
||||
AudioEngine::instance().setOutputGain(gain);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_realtimevoice_VoiceEngine_nativeSetTargetMode(JNIEnv*, jobject,
|
||||
jboolean enabled,
|
||||
jfloat targetF0Hz) {
|
||||
AudioEngine::instance().setTargetMode(enabled == JNI_TRUE, targetF0Hz);
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL
|
||||
Java_com_voicecraft_realtimevoice_VoiceEngine_nativeGetStats(JNIEnv* env, jobject) {
|
||||
return env->NewStringUTF(AudioEngine::instance().stats().c_str());
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,209 @@
|
||||
#include "psola.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
void Psola::setup(float sampleRate) {
|
||||
fs_ = sampleRate;
|
||||
inRing_.assign(kInCap, 0.f);
|
||||
outRing_.assign(kOutCap, 0.f);
|
||||
normRing_.assign(kOutCap, 0.f);
|
||||
reset();
|
||||
}
|
||||
|
||||
void Psola::reset() {
|
||||
std::fill(inRing_.begin(), inRing_.end(), 0.f);
|
||||
std::fill(outRing_.begin(), outRing_.end(), 0.f);
|
||||
std::fill(normRing_.begin(), normRing_.end(), 0.f);
|
||||
inPos_ = 0;
|
||||
outConsumed_ = 0;
|
||||
inPhase_ = 0.f;
|
||||
slotCarry_ = 0.f;
|
||||
marks_.clear();
|
||||
underruns_ = 0;
|
||||
// 首个 grain 中心放在延迟处,之前的输出为静音
|
||||
nextSlot_ = kLatencySamples;
|
||||
tIn_ = tInTarget_;
|
||||
tOut_ = tOutTarget_;
|
||||
}
|
||||
|
||||
void Psola::setRatios(float pitchRatio, float formantRatio) {
|
||||
pitchRatio_ = std::max(0.25f, std::min(4.f, pitchRatio));
|
||||
formant_ = std::max(0.5f, std::min(2.f, formantRatio));
|
||||
}
|
||||
|
||||
void Psola::setSmoothing(float s) {
|
||||
smoothing_ = std::max(0.001f, std::min(0.5f, s));
|
||||
}
|
||||
|
||||
void Psola::setPeriodTargets(float tIn, float tOut) {
|
||||
// 输入周期限幅:f0 ∈ [60, 500] Hz
|
||||
tInTarget_ = std::max(fs_ / 500.f, std::min(fs_ / 60.f, tIn));
|
||||
// 输出周期限幅:f0_out ≥ 143 Hz(女声音域足够,同时保住延迟预算)
|
||||
tOutTarget_ = std::max(40.f, std::min(336.f, tOut));
|
||||
}
|
||||
|
||||
bool Psola::tryProduceGrain() {
|
||||
// grain 源半长(重采样前):使重采样后 ≈ 2×tOut_
|
||||
int halfS = (int)std::ceil(tOut_ * formant_);
|
||||
halfS = std::min(halfS, 448); // 限制前瞻,保住延迟预算
|
||||
|
||||
// 产出上界:槽位对应的输入位置必须已到齐(防单标记无限产出)
|
||||
const long targetIn = nextSlot_ - kLatencySamples;
|
||||
if (targetIn > inPos_ - halfS - 1) return false;
|
||||
|
||||
// 丢弃过小或过期的标记:保留最接近 targetIn 的标记
|
||||
while (!marks_.empty()) {
|
||||
const long m0 = marks_.front();
|
||||
if (m0 < halfS) {
|
||||
marks_.pop_front();
|
||||
continue;
|
||||
}
|
||||
if (marks_.size() >= 2 && (float)marks_[1] <= (float)targetIn) {
|
||||
marks_.pop_front();
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (marks_.empty()) return false;
|
||||
|
||||
const long m = marks_.front();
|
||||
const int srcLen = 2 * halfS + 1;
|
||||
|
||||
// 需要的输入样本是否到齐(前瞻部分尚未到达则等待)
|
||||
if (inPos_ <= m + halfS) return false;
|
||||
|
||||
// 输出侧重采样后的 grain 长度
|
||||
int lr = (int)std::round((float)srcLen / formant_);
|
||||
lr = std::max(4, lr);
|
||||
|
||||
grainSrc_.resize((size_t)srcLen);
|
||||
grainWin_.resize((size_t)lr);
|
||||
winBuf_.resize((size_t)lr);
|
||||
|
||||
// grain 提取:源片段 → Catmull-Rom 重采样(抑混叠)→ Hann 窗
|
||||
auto extractGrain = [&](long center, std::vector<float>& dst) {
|
||||
for (int i = 0; i < srcLen; ++i) {
|
||||
grainSrc_[(size_t)i] = readIn(center - halfS + i);
|
||||
}
|
||||
for (int j = 0; j < lr; ++j) {
|
||||
const float srcPos = (float)j * formant_;
|
||||
const int i1 = (int)srcPos;
|
||||
const float t = srcPos - (float)i1;
|
||||
const int i0 = std::max(0, i1 - 1);
|
||||
const int i2 = std::min(i1 + 1, srcLen - 1);
|
||||
const int i3 = std::min(i1 + 2, srcLen - 1);
|
||||
const float p0 = grainSrc_[(size_t)i0];
|
||||
const float p1 = grainSrc_[(size_t)i1];
|
||||
const float p2 = grainSrc_[(size_t)i2];
|
||||
const float p3 = grainSrc_[(size_t)i3];
|
||||
float v = 0.5f * ((2.f * p1) +
|
||||
(-p0 + p2) * t +
|
||||
(2.f * p0 - 5.f * p1 + 4.f * p2 - p3) * t * t +
|
||||
(-p0 + 3.f * p1 - 3.f * p2 + p3) * t * t * t);
|
||||
const float w = 0.5f * (1.f - std::cos(2.f * 3.14159265f * (float)j / (float)(lr - 1)));
|
||||
dst[(size_t)j] = v * w;
|
||||
if (&dst == &grainWin_) winBuf_[(size_t)j] = w; // 记录窗值供 OLA 归一化
|
||||
}
|
||||
};
|
||||
|
||||
extractGrain(m, grainWin_);
|
||||
|
||||
// 复用渐变(治"模糊"):升调时同一标记被多槽位复用,原样复制会产生梳状模糊;
|
||||
// 向下一标记的 grain 按相位比例渐变,相邻槽位波形不再相同
|
||||
long mNext = -1;
|
||||
for (long cand : marks_) {
|
||||
if (cand > m) {
|
||||
mNext = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (mNext > 0 && targetIn > m && mNext + halfS < inPos_) {
|
||||
const float blend = std::min(1.f, (float)(targetIn - m) / (float)(mNext - m));
|
||||
if (blend > 0.02f) {
|
||||
grainNext_.resize((size_t)lr);
|
||||
extractGrain(mNext, grainNext_);
|
||||
for (int j = 0; j < lr; ++j) {
|
||||
grainWin_[(size_t)j] =
|
||||
grainWin_[(size_t)j] * (1.f - blend) + grainNext_[(size_t)j] * blend;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// OLA:grain 中心对齐 nextSlot_,写入输出环 + 窗口和环(归一化用)
|
||||
const long startAbs = nextSlot_ - lr / 2;
|
||||
for (int j = 0; j < lr; ++j) {
|
||||
const long absOut = startAbs + j;
|
||||
// 未消费区域才可写(防止覆盖已弹出数据)
|
||||
if (absOut >= outConsumed_ && absOut < outConsumed_ + kOutCap) {
|
||||
outRing_[(size_t)(absOut & (kOutCap - 1))] += grainWin_[(size_t)j];
|
||||
normRing_[(size_t)(absOut & (kOutCap - 1))] += winBuf_[(size_t)j];
|
||||
}
|
||||
}
|
||||
|
||||
// 槽位推进:整数步进 + 小数余量累积(避免 tOut 截断造成时间轴漂移)
|
||||
slotCarry_ += std::max(1.f, tOut_);
|
||||
const long adv = (long)slotCarry_;
|
||||
slotCarry_ -= (float)adv;
|
||||
nextSlot_ += adv;
|
||||
|
||||
// 平滑周期(避免 f0 抖动,系数可配置)
|
||||
tIn_ += (tInTarget_ - tIn_) * smoothing_;
|
||||
tOut_ += (tOutTarget_ - tOut_) * smoothing_;
|
||||
return true;
|
||||
}
|
||||
|
||||
void Psola::process(const float* in, float* out, int n) {
|
||||
// 1. 输入写入环形缓冲,生成音高标记
|
||||
for (int i = 0; i < n; ++i) {
|
||||
inRing_[(size_t)(inPos_ & (kInCap - 1))] = in[i];
|
||||
++inPos_;
|
||||
inPhase_ += 1.f;
|
||||
if (inPhase_ >= tIn_) {
|
||||
inPhase_ -= tIn_;
|
||||
// 基因同步标记:在周期窗口内找波形绝对峰(对齐声门闭合相位)。
|
||||
// 标记相位一致 → grain 拼接处相位连续 → 谐波间噪声大降(治"模糊"的核心)
|
||||
const long center = inPos_ - 1;
|
||||
const int half = std::max(2, (int)(tIn_ * 0.25f));
|
||||
long bestPos = center;
|
||||
float bestVal = -1.f;
|
||||
for (long p = center - half; p <= center + half; ++p) {
|
||||
if (p < 0 || p >= inPos_) continue;
|
||||
const float v = std::fabs(readIn(p));
|
||||
if (v > bestVal) {
|
||||
bestVal = v;
|
||||
bestPos = p;
|
||||
}
|
||||
}
|
||||
marks_.push_back(bestPos);
|
||||
if (marks_.size() > 64) marks_.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 能产多少 grain 产多少
|
||||
while (tryProduceGrain()) {
|
||||
}
|
||||
|
||||
// 3. 弹出输出:已"定型"的样本数 = nextSlot_ - tOut_
|
||||
long ready = nextSlot_ - (long)std::ceil(tOut_) - outConsumed_;
|
||||
if (ready < 0) ready = 0;
|
||||
const int canCopy = (int)std::min((long)n, ready);
|
||||
|
||||
for (int i = 0; i < canCopy; ++i) {
|
||||
const size_t idx = (size_t)((outConsumed_ + i) & (kOutCap - 1));
|
||||
const float wsum = normRing_[idx];
|
||||
// 窗口和归一化:消除重叠叠加的幅度纹波("模糊/沙哑"的重要来源)
|
||||
out[i] = wsum > 0.05f ? outRing_[idx] / wsum : outRing_[idx];
|
||||
}
|
||||
for (int i = canCopy; i < n; ++i) {
|
||||
out[i] = 0.f;
|
||||
}
|
||||
if (canCopy < n) ++underruns_;
|
||||
|
||||
// 清掉已消费的区域,避免陈旧能量残留
|
||||
for (int i = 0; i < canCopy; ++i) {
|
||||
const size_t idx = (size_t)((outConsumed_ + i) & (kOutCap - 1));
|
||||
outRing_[idx] = 0.f;
|
||||
normRing_[idx] = 0.f;
|
||||
}
|
||||
outConsumed_ += n;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
// 流式 TD-PSOLA 变调引擎
|
||||
//
|
||||
// 原理(男变女的关键):
|
||||
// 1. 音高:按输出周期 T_out 重排音高粒(grain)——决定 f0
|
||||
// 2. 共振峰:把 grain 时间轴按 formantRatio 加速重采样——频谱整体搬移
|
||||
// (纯升调=小黄人;共振峰同步上移=真实女声,即 VTLP 等效实现)
|
||||
//
|
||||
// 流式约束:输入输出 1:1 等长,固定延迟 kLatencySamples。
|
||||
|
||||
#include <vector>
|
||||
#include <deque>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
class Psola {
|
||||
public:
|
||||
// 固定处理延迟(样本数,48kHz 下约 16.7ms)
|
||||
// 依据:输出周期上限 336(f0≥143Hz,女声场景足够)× (1 + formant上限1.33) ≈ 784
|
||||
static constexpr int kLatencySamples = 800;
|
||||
static constexpr int kInCap = 16384; // 输入环形缓冲容量(2 的幂)
|
||||
static constexpr int kOutCap = 16384; // 输出环形缓冲容量(2 的幂)
|
||||
|
||||
void setup(float sampleRate);
|
||||
void reset();
|
||||
|
||||
// pitchRatio: 输出/输入 f0 比(1.0=不变,2^(9/12)≈1.68 = +9 半音)
|
||||
// formantRatio: 共振峰搬移比(1.2 = 声道缩短 20%,女声化)
|
||||
void setRatios(float pitchRatio, float formantRatio);
|
||||
|
||||
// 由基频检测驱动的周期目标(样本数),内部带限幅与平滑
|
||||
void setPeriodTargets(float tIn, float tOut);
|
||||
|
||||
// 平滑系数(0.001=极平滑,0.1=快速跟随;防 f0 抖动/颤音)
|
||||
void setSmoothing(float s);
|
||||
|
||||
// 流式处理:in → out,长度 n(约 4~10ms 一块)
|
||||
void process(const float* in, float* out, int n);
|
||||
|
||||
int underruns() const { return underruns_; }
|
||||
float currentTOut() const { return tOut_; }
|
||||
|
||||
private:
|
||||
bool tryProduceGrain();
|
||||
float readIn(long absPos) const {
|
||||
return inRing_[(size_t)(absPos & (kInCap - 1))];
|
||||
}
|
||||
|
||||
float fs_ = 48000.f;
|
||||
|
||||
// 输入/输出周期(样本数),带平滑
|
||||
float tIn_ = 400.f, tInTarget_ = 400.f;
|
||||
float tOut_ = 400.f, tOutTarget_ = 400.f;
|
||||
float pitchRatio_ = 1.f, formant_ = 1.f;
|
||||
float smoothing_ = 0.05f;
|
||||
|
||||
std::vector<float> inRing_;
|
||||
std::vector<float> outRing_;
|
||||
std::vector<float> normRing_; // OLA 窗口和(归一化除纹波,治"模糊")
|
||||
std::vector<float> winBuf_; // 当前 grain 的窗函数值
|
||||
long inPos_ = 0; // 已写入的输入绝对位置
|
||||
long outConsumed_ = 0; // 已弹出的输出绝对位置
|
||||
long nextSlot_ = 0; // 下一个 grain 中心的输出绝对位置
|
||||
float inPhase_ = 0.f; // 输入侧音高标记相位
|
||||
float slotCarry_ = 0.f; // 输出槽位推进的小数余量(防时间轴漂移)
|
||||
std::deque<long> marks_;
|
||||
int underruns_ = 0;
|
||||
|
||||
// grain 重采样暂存
|
||||
std::vector<float> grainSrc_;
|
||||
std::vector<float> grainWin_;
|
||||
std::vector<float> grainNext_; // 复用渐变用:下一标记的 grain
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
|
||||
// YIN 基频检测(de Cheveigné & Kawahara 2002)
|
||||
// 输入固定长度窗口,返回 f0(Hz);清音/置信度不足返回 0
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
|
||||
class Yin {
|
||||
public:
|
||||
void setup(float sampleRate, int windowSize) {
|
||||
fs_ = sampleRate;
|
||||
half_ = windowSize / 2;
|
||||
d_.assign(half_ + 1, 0.f);
|
||||
cmnd_.assign(half_ + 1, 0.f);
|
||||
}
|
||||
|
||||
void setRange(float fMin, float fMax) {
|
||||
fMin_ = fMin;
|
||||
fMax_ = fMax;
|
||||
}
|
||||
|
||||
// x 至少需要 windowSize 个样本(本实现用前 half_ + tauMax 个)
|
||||
float detect(const float* x) {
|
||||
const int tauMax = std::min(half_ - 1, (int)(fs_ / fMin_));
|
||||
const int tauMin = std::max(2, (int)(fs_ / fMax_));
|
||||
if (tauMin >= tauMax) return 0.f;
|
||||
|
||||
// 差分函数 d(tau)
|
||||
for (int tau = 0; tau <= tauMax; ++tau) {
|
||||
float sum = 0.f;
|
||||
for (int i = 0; i < half_; ++i) {
|
||||
const float diff = x[i] - x[i + tau];
|
||||
sum += diff * diff;
|
||||
}
|
||||
d_[tau] = sum;
|
||||
}
|
||||
|
||||
// 累积均值归一化 d'(tau)
|
||||
cmnd_[0] = 1.f;
|
||||
float running = 0.f;
|
||||
for (int tau = 1; tau <= tauMax; ++tau) {
|
||||
running += d_[tau];
|
||||
cmnd_[tau] = running > 0.f ? d_[tau] * tau / running : 1.f;
|
||||
}
|
||||
|
||||
// 绝对阈值取第一个谷
|
||||
const float thresh = 0.15f;
|
||||
int tauEst = -1;
|
||||
for (int tau = tauMin; tau <= tauMax; ++tau) {
|
||||
if (cmnd_[tau] < thresh) {
|
||||
while (tau + 1 <= tauMax && cmnd_[tau + 1] < cmnd_[tau]) ++tau;
|
||||
tauEst = tau;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (tauEst < 0) {
|
||||
// 未达阈值:全局最小兜底,置信度不足判清音
|
||||
float best = 1e9f;
|
||||
for (int tau = tauMin; tau <= tauMax; ++tau) {
|
||||
if (cmnd_[tau] < best) {
|
||||
best = cmnd_[tau];
|
||||
tauEst = tau;
|
||||
}
|
||||
}
|
||||
if (best > 0.55f) return 0.f;
|
||||
}
|
||||
|
||||
// 抛物线插值细化周期
|
||||
float betterTau = (float)tauEst;
|
||||
if (tauEst > tauMin && tauEst < tauMax) {
|
||||
const float s0 = cmnd_[tauEst - 1];
|
||||
const float s1 = cmnd_[tauEst];
|
||||
const float s2 = cmnd_[tauEst + 1];
|
||||
const float denom = 2.f * (2.f * s1 - s2 - s0);
|
||||
if (std::fabs(denom) > 1e-9f) betterTau += (s2 - s0) / denom;
|
||||
}
|
||||
return fs_ / betterTau;
|
||||
}
|
||||
|
||||
private:
|
||||
float fs_ = 48000.f;
|
||||
float fMin_ = 65.f;
|
||||
float fMax_ = 500.f;
|
||||
int half_ = 512;
|
||||
std::vector<float> d_;
|
||||
std::vector<float> cmnd_;
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.voicecraft.realtimevoice;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
import android.os.PowerManager;
|
||||
|
||||
/**
|
||||
* 前台服务:把本进程钉在前台,防止双机模式下系统(vivo 后台管控等)杀掉音频。
|
||||
* 附带唤醒锁,息屏后音频管线继续运行。
|
||||
*/
|
||||
public class AudioFgService extends Service {
|
||||
|
||||
private static final String CHANNEL_ID = "voice_m0_running";
|
||||
private PowerManager.WakeLock wakeLock;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
|
||||
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
NotificationChannel ch = new NotificationChannel(
|
||||
CHANNEL_ID, "实时变声运行中", NotificationManager.IMPORTANCE_LOW);
|
||||
ch.setShowBadge(false);
|
||||
nm.createNotificationChannel(ch);
|
||||
|
||||
Notification notif = new Notification.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(android.R.drawable.ic_btn_speak_now)
|
||||
.setContentTitle("实时变声运行中")
|
||||
.setContentText("双机模式:音频管线保持工作,点击应用可调参")
|
||||
.setOngoing(true)
|
||||
.build();
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
startForeground(1, notif, ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE);
|
||||
} else {
|
||||
startForeground(1, notif);
|
||||
}
|
||||
|
||||
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
|
||||
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "voice_m0:audio");
|
||||
wakeLock.setReferenceCounted(false);
|
||||
wakeLock.acquire();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
if (wakeLock != null && wakeLock.isHeld()) wakeLock.release();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package com.voicecraft.realtimevoice;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.widget.Button;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.RadioGroup;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
/**
|
||||
* M0 实时变声测试界面:
|
||||
* 麦克风 → DSP(变调 + 共振峰搬移)→ 扬声器/耳机 实时回放。
|
||||
* 全部参数自动保存到 voice_config.json(可手工编辑,重启生效)。
|
||||
* 戴耳机测试(避免扬声器回授啸叫)。
|
||||
*/
|
||||
public class MainActivity extends Activity {
|
||||
|
||||
private static final int REQ_AUDIO = 100;
|
||||
|
||||
private VoiceEngine engine;
|
||||
private VoiceConfig cfg;
|
||||
|
||||
private Button btnStart;
|
||||
private SeekBar sbPitch, sbFormant, sbStrength, sbGain;
|
||||
private SeekBar sbEqFreq, sbEqGain, sbGate, sbF0Min, sbF0Max, sbSmooth;
|
||||
private CheckBox cbBypass;
|
||||
private TextView tvStatus, tvValues;
|
||||
|
||||
private boolean running = false;
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private final Runnable statsPoll = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (running) {
|
||||
tvStatus.setText(engine.nativeGetStats());
|
||||
handler.postDelayed(this, 500);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
engine = new VoiceEngine();
|
||||
cfg = VoiceConfig.load(this);
|
||||
|
||||
btnStart = findViewById(R.id.btnStart);
|
||||
sbPitch = findViewById(R.id.sbPitch);
|
||||
sbFormant = findViewById(R.id.sbFormant);
|
||||
sbStrength = findViewById(R.id.sbStrength);
|
||||
sbGain = findViewById(R.id.sbGain);
|
||||
sbEqFreq = findViewById(R.id.sbEqFreq);
|
||||
sbEqGain = findViewById(R.id.sbEqGain);
|
||||
sbGate = findViewById(R.id.sbGate);
|
||||
sbF0Min = findViewById(R.id.sbF0Min);
|
||||
sbF0Max = findViewById(R.id.sbF0Max);
|
||||
sbSmooth = findViewById(R.id.sbSmooth);
|
||||
cbBypass = findViewById(R.id.cbBypass);
|
||||
tvStatus = findViewById(R.id.tvStatus);
|
||||
tvValues = findViewById(R.id.tvValues);
|
||||
RadioGroup rgPresets = findViewById(R.id.rgPresets);
|
||||
|
||||
applyConfigToUi();
|
||||
|
||||
// 滑杆:拖动中实时生效(pushParams),松手时持久化(save)
|
||||
SeekBar.OnSeekBarChangeListener live = new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override
|
||||
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
|
||||
pushParams();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStartTrackingTouch(SeekBar seekBar) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStopTrackingTouch(SeekBar seekBar) {
|
||||
cfg.save(MainActivity.this);
|
||||
}
|
||||
};
|
||||
SeekBar[] bars = {sbPitch, sbFormant, sbStrength, sbGain,
|
||||
sbEqFreq, sbEqGain, sbGate, sbF0Min, sbF0Max, sbSmooth};
|
||||
for (SeekBar b : bars) b.setOnSeekBarChangeListener(live);
|
||||
|
||||
cbBypass.setOnCheckedChangeListener((buttonView, isChecked) -> {
|
||||
pushParams();
|
||||
cfg.save(this);
|
||||
});
|
||||
|
||||
// 预设来自配置文件(可手工改 voice_config.json 里的 presets)
|
||||
rgPresets.setOnCheckedChangeListener((group, checkedId) -> {
|
||||
int idx;
|
||||
if (checkedId == R.id.rbLady) idx = 1;
|
||||
else if (checkedId == R.id.rbLoli) idx = 2;
|
||||
else if (checkedId == R.id.rbNeutral) idx = 3;
|
||||
else idx = 0;
|
||||
sbPitch.setProgress((int) cfg.presets[idx][0]);
|
||||
sbFormant.setProgress((int) ((cfg.presets[idx][1] - 1f) * 100f));
|
||||
sbStrength.setProgress(100);
|
||||
pushParams();
|
||||
cfg.save(this);
|
||||
});
|
||||
|
||||
btnStart.setOnClickListener(v -> {
|
||||
if (running) {
|
||||
stopEngine();
|
||||
} else {
|
||||
ensureMicPermissionThenStart();
|
||||
}
|
||||
});
|
||||
|
||||
pushParams();
|
||||
tvStatus.setText("未启动 — 请戴耳机测试,点击「开始变声」");
|
||||
}
|
||||
|
||||
/** 把配置值映射到各滑杆 */
|
||||
private void applyConfigToUi() {
|
||||
sbPitch.setProgress(Math.round(cfg.pitchSemitones));
|
||||
sbFormant.setProgress(Math.round((cfg.formantRatio - 1f) * 100f));
|
||||
sbStrength.setProgress(Math.round(cfg.strength * 100f));
|
||||
sbGain.setProgress(Math.max(0, Math.round((cfg.outputGain - 0.1f) * 100f)));
|
||||
sbEqFreq.setProgress(Math.round((cfg.eqFreqHz - 500f) / 100f));
|
||||
sbEqGain.setProgress(Math.round(cfg.eqGainDb * 2f));
|
||||
sbGate.setProgress(Math.round(cfg.gateThreshold * 5000f));
|
||||
sbF0Min.setProgress(Math.round(cfg.f0MinHz - 40f));
|
||||
sbF0Max.setProgress(Math.round(cfg.f0MaxHz - 300f));
|
||||
sbSmooth.setProgress(Math.max(0, Math.round(cfg.smoothing * 1000f) - 1));
|
||||
cbBypass.setChecked(cfg.bypass);
|
||||
}
|
||||
|
||||
/** 把滑杆当前值映射回配置并下发引擎 */
|
||||
private void pushParams() {
|
||||
cfg.pitchSemitones = sbPitch.getProgress();
|
||||
cfg.formantRatio = 1f + sbFormant.getProgress() / 100f;
|
||||
cfg.strength = sbStrength.getProgress() / 100f;
|
||||
cfg.outputGain = 0.1f + sbGain.getProgress() / 100f;
|
||||
cfg.eqFreqHz = 500f + sbEqFreq.getProgress() * 100f;
|
||||
cfg.eqGainDb = sbEqGain.getProgress() / 2f;
|
||||
cfg.gateThreshold = sbGate.getProgress() / 5000f;
|
||||
cfg.f0MinHz = 40f + sbF0Min.getProgress();
|
||||
cfg.f0MaxHz = 300f + sbF0Max.getProgress();
|
||||
cfg.smoothing = (sbSmooth.getProgress() + 1) / 1000f;
|
||||
cfg.bypass = cbBypass.isChecked();
|
||||
|
||||
engine.nativeSetParams(cfg.pitchSemitones, cfg.formantRatio, cfg.strength,
|
||||
cfg.eqFreqHz, cfg.eqGainDb, cfg.gateThreshold,
|
||||
cfg.f0MinHz, cfg.f0MaxHz, cfg.smoothing, cfg.bypass);
|
||||
engine.nativeSetOutputGain(cfg.outputGain);
|
||||
engine.nativeSetTargetMode(cfg.targetMode, cfg.targetF0Hz);
|
||||
|
||||
tvValues.setText(String.format(
|
||||
"音调 +%.0f 半音 | 共振峰 ×%.2f | 强度 %d%% | 增益 ×%.2f | EQ %.0fHz/+%.1fdB%s",
|
||||
cfg.pitchSemitones, cfg.formantRatio, sbStrength.getProgress(),
|
||||
cfg.outputGain, cfg.eqFreqHz, cfg.eqGainDb,
|
||||
cfg.bypass ? " | 旁路直通" : ""));
|
||||
}
|
||||
|
||||
private void ensureMicPermissionThenStart() {
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, REQ_AUDIO);
|
||||
} else {
|
||||
startEngine();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||
if (requestCode == REQ_AUDIO
|
||||
&& grantResults.length > 0
|
||||
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
|
||||
startEngine();
|
||||
} else {
|
||||
Toast.makeText(this, "需要录音权限才能变声", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void startEngine() {
|
||||
pushParams();
|
||||
if (engine.nativeStart(0)) {
|
||||
running = true;
|
||||
btnStart.setText("停止");
|
||||
handler.post(statsPoll);
|
||||
// 双机模式:前台服务 + 常亮,防止息屏/后台管控杀死音频
|
||||
Intent svc = new Intent(this, AudioFgService.class);
|
||||
if (android.os.Build.VERSION.SDK_INT >= 26) {
|
||||
startForegroundService(svc);
|
||||
} else {
|
||||
startService(svc);
|
||||
}
|
||||
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
} else {
|
||||
tvStatus.setText("音频启动失败 — 请检查录音权限或是否被其他应用占用");
|
||||
}
|
||||
}
|
||||
|
||||
private void stopEngine() {
|
||||
running = false;
|
||||
handler.removeCallbacks(statsPoll);
|
||||
engine.nativeStop();
|
||||
btnStart.setText("开始变声");
|
||||
tvStatus.setText("已停止");
|
||||
cfg.save(this);
|
||||
stopService(new Intent(this, AudioFgService.class));
|
||||
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
stopEngine();
|
||||
super.onDestroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.voicecraft.realtimevoice;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 变声参数配置 —— JSON 文件持久化,全部参数可手工调试。
|
||||
*
|
||||
* 配置文件位置(可用 adb push / 文件管理器直接编辑,重启 App 生效):
|
||||
* /sdcard/Android/data/com.voicecraft.realtimevoice/files/voice_config.json
|
||||
*
|
||||
* 参数含义(调"像不像女声"就动这几个):
|
||||
* pitchSemitones 音调(半音) 男变女约 +5~+12,越高越"亮"
|
||||
* formantRatio 共振峰搬移比 1.15~1.25 自然区间,越高越"女"(防小黄人的核心)
|
||||
* strength 效果强度 0~1 整体效果按比例缩放
|
||||
* eqFreqHz 亮度 EQ 频点 500~8000Hz
|
||||
* eqGainDb 亮度 EQ 增益 0~10dB,女声"空气感"
|
||||
* gateThreshold 噪声门阈值 0~0.01,越低越灵敏(防切字)
|
||||
* f0MinHz/f0MaxHz 基频检测范围 限制 YIN 搜索区间,提高检测稳定
|
||||
* smoothing 参数平滑系数 0.001~0.1,越小越平滑(防抖/防颤音)
|
||||
*/
|
||||
public class VoiceConfig {
|
||||
|
||||
private static final String TAG = "VoiceConfig";
|
||||
|
||||
public float pitchSemitones = 9f;
|
||||
public float formantRatio = 1.20f;
|
||||
public float strength = 1f;
|
||||
public float eqFreqHz = 3000f;
|
||||
public float eqGainDb = 3f;
|
||||
public float gateThreshold = 0.006f;
|
||||
public float f0MinHz = 65f;
|
||||
public float f0MaxHz = 500f;
|
||||
public float smoothing = 0.05f;
|
||||
public boolean bypass = false;
|
||||
|
||||
/** 输出增益(0.1~2.0):双机线路模式下匹配目标手机麦克风电平 */
|
||||
public float outputGain = 1f;
|
||||
|
||||
/** 目标音高模式:输出 f0 锚定 targetF0Hz(深沉嗓音自动多补),false=按半音比例变调 */
|
||||
public boolean targetMode = false;
|
||||
|
||||
/** 目标音高(Hz),御姐约 205 */
|
||||
public float targetF0Hz = 205f;
|
||||
|
||||
// 预设 {音调半音, 共振峰比},顺序固定对应界面:少女 / 御姐 / 萝莉 / 中性女
|
||||
public float[][] presets = {
|
||||
{9f, 1.20f},
|
||||
{7f, 1.15f},
|
||||
{12f, 1.25f},
|
||||
{5f, 1.12f},
|
||||
};
|
||||
|
||||
public static File fileOf(Context ctx) {
|
||||
File dir = ctx.getExternalFilesDir(null);
|
||||
if (dir == null) dir = ctx.getFilesDir();
|
||||
return new File(dir, "voice_config.json");
|
||||
}
|
||||
|
||||
/** 读取配置;文件不存在或损坏时返回默认值(并尝试写出默认文件供后续编辑) */
|
||||
public static VoiceConfig load(Context ctx) {
|
||||
VoiceConfig cfg = new VoiceConfig();
|
||||
File f = fileOf(ctx);
|
||||
if (!f.exists()) {
|
||||
cfg.save(ctx);
|
||||
return cfg;
|
||||
}
|
||||
try (FileInputStream in = new FileInputStream(f)) {
|
||||
byte[] buf = new byte[(int) f.length()];
|
||||
int off = 0;
|
||||
while (off < buf.length) {
|
||||
int r = in.read(buf, off, buf.length - off);
|
||||
if (r < 0) break;
|
||||
off += r;
|
||||
}
|
||||
cfg.fromJson(new JSONObject(new String(buf, 0, off, StandardCharsets.UTF_8)));
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "配置读取失败,使用默认值: " + e.getMessage());
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
public void save(Context ctx) {
|
||||
File f = fileOf(ctx);
|
||||
try (FileOutputStream out = new FileOutputStream(f)) {
|
||||
out.write(toJson().toString(2).getBytes(StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "配置保存失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private JSONObject toJson() throws Exception {
|
||||
JSONObject root = new JSONObject();
|
||||
JSONObject p = new JSONObject();
|
||||
p.put("pitchSemitones", pitchSemitones);
|
||||
p.put("formantRatio", formantRatio);
|
||||
p.put("strength", strength);
|
||||
p.put("eqFreqHz", eqFreqHz);
|
||||
p.put("eqGainDb", eqGainDb);
|
||||
p.put("gateThreshold", gateThreshold);
|
||||
p.put("f0MinHz", f0MinHz);
|
||||
p.put("f0MaxHz", f0MaxHz);
|
||||
p.put("smoothing", smoothing);
|
||||
p.put("bypass", bypass);
|
||||
p.put("outputGain", outputGain);
|
||||
p.put("targetMode", targetMode);
|
||||
p.put("targetF0Hz", targetF0Hz);
|
||||
root.put("params", p);
|
||||
|
||||
String[] names = {"少女", "御姐", "萝莉", "中性女"};
|
||||
JSONArray arr = new JSONArray();
|
||||
for (int i = 0; i < presets.length && i < names.length; i++) {
|
||||
JSONObject one = new JSONObject();
|
||||
one.put("name", names[i]);
|
||||
one.put("pitchSemitones", presets[i][0]);
|
||||
one.put("formantRatio", presets[i][1]);
|
||||
arr.put(one);
|
||||
}
|
||||
root.put("presets", arr);
|
||||
root.put("version", 1);
|
||||
return root;
|
||||
}
|
||||
|
||||
private void fromJson(JSONObject root) throws Exception {
|
||||
JSONObject p = root.optJSONObject("params");
|
||||
if (p != null) {
|
||||
pitchSemitones = (float) p.optDouble("pitchSemitones", pitchSemitones);
|
||||
formantRatio = (float) p.optDouble("formantRatio", formantRatio);
|
||||
strength = (float) p.optDouble("strength", strength);
|
||||
eqFreqHz = (float) p.optDouble("eqFreqHz", eqFreqHz);
|
||||
eqGainDb = (float) p.optDouble("eqGainDb", eqGainDb);
|
||||
gateThreshold = (float) p.optDouble("gateThreshold", gateThreshold);
|
||||
f0MinHz = (float) p.optDouble("f0MinHz", f0MinHz);
|
||||
f0MaxHz = (float) p.optDouble("f0MaxHz", f0MaxHz);
|
||||
smoothing = (float) p.optDouble("smoothing", smoothing);
|
||||
bypass = p.optBoolean("bypass", bypass);
|
||||
outputGain = (float) p.optDouble("outputGain", outputGain);
|
||||
targetMode = p.optBoolean("targetMode", targetMode);
|
||||
targetF0Hz = (float) p.optDouble("targetF0Hz", targetF0Hz);
|
||||
}
|
||||
JSONArray arr = root.optJSONArray("presets");
|
||||
if (arr != null) {
|
||||
for (int i = 0; i < arr.length() && i < presets.length; i++) {
|
||||
JSONObject one = arr.optJSONObject(i);
|
||||
if (one == null) continue;
|
||||
presets[i][0] = (float) one.optDouble("pitchSemitones", presets[i][0]);
|
||||
presets[i][1] = (float) one.optDouble("formantRatio", presets[i][1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.voicecraft.realtimevoice;
|
||||
|
||||
/**
|
||||
* 变声引擎 JNI 包装(M0 测试版)
|
||||
* 引擎为纯 native(C++),Java 只做参数传递与状态读取。
|
||||
*/
|
||||
public class VoiceEngine {
|
||||
|
||||
static {
|
||||
System.loadLibrary("voiceengine");
|
||||
}
|
||||
|
||||
/** 启动音频双工(preferredRate=0 表示跟随设备默认采样率) */
|
||||
public native boolean nativeStart(int preferredRate);
|
||||
|
||||
/** 停止音频并释放流 */
|
||||
public native void nativeStop();
|
||||
|
||||
/**
|
||||
* 设置变声参数(全参数版,与 voice_config.json 一一对应)
|
||||
*
|
||||
* @param pitchSemis 音调(半音,男变女约 +5~+12)
|
||||
* @param formant 共振峰比(1.15~1.25,越大越"女")
|
||||
* @param strength 效果强度 0~1
|
||||
* @param eqFreqHz 亮度 EQ 频点(500~8000Hz)
|
||||
* @param eqGainDb 亮度 EQ 增益(0~10dB)
|
||||
* @param gateThreshold 噪声门阈值(0~0.01)
|
||||
* @param f0MinHz 基频检测下限(40~200Hz)
|
||||
* @param f0MaxHz 基频检测上限(300~800Hz)
|
||||
* @param smoothing 参数平滑系数(0.001~0.1,越小越平滑)
|
||||
* @param bypass true=旁路直通(同延迟)
|
||||
*/
|
||||
public native void nativeSetParams(float pitchSemis, float formant, float strength,
|
||||
float eqFreqHz, float eqGainDb, float gateThreshold,
|
||||
float f0MinHz, float f0MaxHz, float smoothing,
|
||||
boolean bypass);
|
||||
|
||||
/** 输出增益(0.1~2.0):双机线路输出时匹配目标手机麦克风电平 */
|
||||
public native void nativeSetOutputGain(float gain);
|
||||
|
||||
/** 目标音高模式:输出 f0 锚定 targetF0Hz(深沉嗓音自动多补),关闭时按半音比例变调 */
|
||||
public native void nativeSetTargetMode(boolean enabled, float targetF0Hz);
|
||||
|
||||
/** 运行统计(采样率/处理耗时/f0/欠载等,中文单行文本) */
|
||||
public native String nativeGetStats();
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/title"
|
||||
android:textSize="20sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tvStatus"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:fontFamily="monospace"
|
||||
android:text="@string/status_idle"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tvValues"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btnStart"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/btn_start" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/label_presets"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<RadioGroup
|
||||
android:id="@+id/rgPresets"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<RadioButton
|
||||
android:id="@+id/rbGirl"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:checked="true"
|
||||
android:text="@string/preset_girl" />
|
||||
|
||||
<RadioButton
|
||||
android:id="@+id/rbLady"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/preset_lady" />
|
||||
|
||||
<RadioButton
|
||||
android:id="@+id/rbLoli"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/preset_loli" />
|
||||
|
||||
<RadioButton
|
||||
android:id="@+id/rbNeutral"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/preset_neutral" />
|
||||
</RadioGroup>
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/label_pitch" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbPitch"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="24" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_formant" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbFormant"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="40" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_strength" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbStrength"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="100" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_gain" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbGain"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="190" />
|
||||
|
||||
<CheckBox
|
||||
android:id="@+id/cbBypass"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_bypass" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/label_advanced"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_eq_freq" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbEqFreq"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="75" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_eq_gain" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbEqGain"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="20" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_gate" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbGate"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="50" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_f0min" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbF0Min"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="80" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_f0max" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbF0Max"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="500" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/label_smooth" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/sbSmooth"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:max="100" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/tips_config"
|
||||
android:textSize="12sp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/tips"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">实时变声M0</string>
|
||||
<string name="title">实时男变女 · 引擎原型</string>
|
||||
<string name="status_idle">未启动 — 请戴耳机测试,点击「开始变声」</string>
|
||||
<string name="btn_start">开始变声</string>
|
||||
<string name="btn_stop">停止</string>
|
||||
<string name="label_presets">预设</string>
|
||||
<string name="preset_girl">少女</string>
|
||||
<string name="preset_lady">御姐</string>
|
||||
<string name="preset_loli">萝莉</string>
|
||||
<string name="preset_neutral">中性女</string>
|
||||
<string name="label_pitch">音调(半音,男变女约 +5~+12)</string>
|
||||
<string name="label_formant">共振峰搬移(越大越“女”,1.15~1.25 为自然区间)</string>
|
||||
<string name="label_strength">效果强度</string>
|
||||
<string name="label_gain">输出增益 ×0.1~2.0(双机线路模式:爆音就降,太小就升)</string>
|
||||
<string name="label_bypass">旁路直通(同延迟 A/B 对比)</string>
|
||||
<string name="label_advanced">高级参数(影响“像不像”,自动保存)</string>
|
||||
<string name="label_eq_freq">亮度 EQ 频点(500~8000Hz)</string>
|
||||
<string name="label_eq_gain">亮度 EQ 增益(0~10dB,女声“空气感”)</string>
|
||||
<string name="label_gate">噪声门阈值(0~0.010,越低越灵敏,防切字)</string>
|
||||
<string name="label_f0min">基频检测下限(40~200Hz)</string>
|
||||
<string name="label_f0max">基频检测上限(300~800Hz)</string>
|
||||
<string name="label_smooth">参数平滑(0.001~0.1,越小越平滑防颤音)</string>
|
||||
<string name="tips_config">配置文件(重启 App 生效,可 adb push 手工调参):\n/sdcard/Android/data/com.voicecraft.realtimevoice/files/voice_config.json</string>
|
||||
<string name="tips">提示:① 戴耳机测试,扬声器外放会啸叫;② 「少女」预设听感达标即可进入 M1(微信注入);③ 本应用只做实时变声回放,不录音、不联网。</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
// 实时变声 M0 — 根构建脚本
|
||||
plugins {
|
||||
id 'com.android.application' version '8.7.3' apply false
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
org.gradle.daemon=true
|
||||
org.gradle.caching=true
|
||||
org.gradle.parallel=true
|
||||
android.useAndroidX=false
|
||||
android.nonTransitiveRClass=true
|
||||
@@ -0,0 +1,19 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven { url 'https://maven.aliyun.com/repository/public' }
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
maven { url 'https://maven.aliyun.com/repository/public' }
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
rootProject.name = 'realtime-voice'
|
||||
include ':app'
|
||||
include ':xposed'
|
||||
@@ -0,0 +1,48 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'com.voicecraft.xposed'
|
||||
compileSdk 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId 'com.voicecraft.xposed'
|
||||
minSdk 24
|
||||
targetSdk 34
|
||||
versionCode 1
|
||||
versionName '0.1.0-m1'
|
||||
|
||||
ndk {
|
||||
abiFilters 'arm64-v8a'
|
||||
}
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
cppFlags '-O2'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path file('src/main/cpp/CMakeLists.txt')
|
||||
version '3.22.1'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// Xposed API 82(经典版,LSPosed 完全兼容)——仅编译期,运行时由框架提供
|
||||
compileOnly 'de.robv.android.xposed:api:82'
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<application
|
||||
android:label="变声注入模块"
|
||||
android:allowBackup="false">
|
||||
|
||||
<!-- Xposed 模块元数据(LSPosed 识别) -->
|
||||
<meta-data
|
||||
android:name="xposedmodule"
|
||||
android:value="true" />
|
||||
<meta-data
|
||||
android:name="xposeddescription"
|
||||
android:value="实时男变女变声注入模块(M1):hook AudioRecord,对微信/QQ 语音实时变声" />
|
||||
<meta-data
|
||||
android:name="xposedminversion"
|
||||
android:value="93" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1 @@
|
||||
com.voicecraft.xposed.HookEntry
|
||||
@@ -0,0 +1,17 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
project(vchangemin LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# 复用 M0 的 DSP 引擎源码(同一份代码,两处部署:测试 App / 注入模块)
|
||||
set(SHARED ${CMAKE_CURRENT_SOURCE_DIR}/../../../../app/src/main/cpp)
|
||||
|
||||
add_library(vchangemin SHARED
|
||||
engine_min.cpp
|
||||
${SHARED}/psola.cpp
|
||||
${SHARED}/dsp_pipeline.cpp)
|
||||
|
||||
target_include_directories(vchangemin PRIVATE ${SHARED})
|
||||
target_compile_options(vchangemin PRIVATE -O2 -Wall)
|
||||
target_link_libraries(vchangemin log)
|
||||
@@ -0,0 +1,103 @@
|
||||
// 注入侧轻量 JNI:只做 buffer 就地变声,不做音频 I/O
|
||||
// DSP 管线复用 M0 的 dsp_pipeline(PSOLA 变调 + 共振峰搬移)
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#include "dsp_pipeline.h"
|
||||
|
||||
namespace {
|
||||
|
||||
std::mutex g_mutex;
|
||||
DspPipeline g_pipeline;
|
||||
std::vector<float> g_in, g_out;
|
||||
bool g_ready = false;
|
||||
|
||||
void processInternal(const short* in, short* out, int n) {
|
||||
g_in.resize((size_t)n);
|
||||
g_out.resize((size_t)n);
|
||||
for (int i = 0; i < n; ++i) g_in[(size_t)i] = (float)in[i] / 32768.f;
|
||||
g_pipeline.process(g_in.data(), g_out.data(), n);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
float v = g_out[(size_t)i] * 32767.f;
|
||||
if (v > 32767.f) v = 32767.f;
|
||||
if (v < -32768.f) v = -32768.f;
|
||||
out[i] = (short)v;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_xposed_VoiceEngineMin_nativeInit(JNIEnv*, jclass, jint sampleRate) {
|
||||
std::lock_guard<std::mutex> lk(g_mutex);
|
||||
g_pipeline.setup((float)sampleRate);
|
||||
g_ready = true;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_xposed_VoiceEngineMin_nativeSetParams(JNIEnv*, jclass,
|
||||
jfloat pitchSemis, jfloat formant,
|
||||
jfloat strength, jfloat eqFreqHz,
|
||||
jfloat eqGainDb, jfloat gateThreshold,
|
||||
jfloat f0MinHz, jfloat f0MaxHz,
|
||||
jfloat smoothing, jboolean bypass) {
|
||||
std::lock_guard<std::mutex> lk(g_mutex);
|
||||
g_pipeline.setParams(pitchSemis, formant, strength,
|
||||
eqFreqHz, eqGainDb, gateThreshold,
|
||||
f0MinHz, f0MaxHz, smoothing, bypass == JNI_TRUE);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_xposed_VoiceEngineMin_nativeSetTargetMode(JNIEnv*, jclass,
|
||||
jboolean enabled,
|
||||
jfloat targetF0Hz) {
|
||||
std::lock_guard<std::mutex> lk(g_mutex);
|
||||
g_pipeline.setTargetMode(enabled == JNI_TRUE, targetF0Hz);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_xposed_VoiceEngineMin_nativeProcessByte(JNIEnv* env, jclass,
|
||||
jbyteArray buf, jint nBytes) {
|
||||
if (nBytes <= 0) return;
|
||||
std::lock_guard<std::mutex> lk(g_mutex);
|
||||
if (!g_ready) return;
|
||||
|
||||
const int n = nBytes / 2;
|
||||
if (n <= 0) return;
|
||||
std::vector<short> tmp((size_t)n);
|
||||
|
||||
jbyte* raw = env->GetByteArrayElements(buf, nullptr);
|
||||
if (raw == nullptr) return;
|
||||
// 16 位 PCM 小端 → short
|
||||
unsigned char* u = reinterpret_cast<unsigned char*>(raw);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
tmp[(size_t)i] = (short)((unsigned short)u[2 * i] | ((unsigned short)u[2 * i + 1] << 8));
|
||||
}
|
||||
processInternal(tmp.data(), tmp.data(), n);
|
||||
// 写回(就地替换)
|
||||
for (int i = 0; i < n; ++i) {
|
||||
u[2 * i] = (unsigned char)(tmp[(size_t)i] & 0xff);
|
||||
u[2 * i + 1] = (unsigned char)((tmp[(size_t)i] >> 8) & 0xff);
|
||||
}
|
||||
env->ReleaseByteArrayElements(buf, raw, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_voicecraft_xposed_VoiceEngineMin_nativeProcessShort(JNIEnv* env, jclass,
|
||||
jshortArray buf, jint n) {
|
||||
if (n <= 0) return;
|
||||
std::lock_guard<std::mutex> lk(g_mutex);
|
||||
if (!g_ready) return;
|
||||
|
||||
jshort* raw = env->GetShortArrayElements(buf, nullptr);
|
||||
if (raw == nullptr) return;
|
||||
processInternal(raw, raw, (int)n);
|
||||
env->ReleaseShortArrayElements(buf, raw, 0);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.voicecraft.xposed;
|
||||
|
||||
import android.media.AudioRecord;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import de.robv.android.xposed.IXposedHookLoadPackage;
|
||||
import de.robv.android.xposed.XC_MethodHook;
|
||||
import de.robv.android.xposed.XposedBridge;
|
||||
import de.robv.android.xposed.XposedHelpers;
|
||||
import de.robv.android.xposed.callbacks.XC_LoadPackage;
|
||||
|
||||
/**
|
||||
* M1 注入入口(L1 Java 层 hook):
|
||||
* 在目标 App(微信/QQ)进程内 hook {@link AudioRecord#read} 全部常用重载,
|
||||
* 读取完成后对 buffer 就地做男变女处理——App 自身无感知。
|
||||
*
|
||||
* 设计要点:
|
||||
* 1. afterHookedMethod 中处理(拿到返回值 = 实际读取的字节/样本数,不越界)
|
||||
* 2. 异常全兜底——hook 出任何岔子都不能带崩宿主 App
|
||||
* 3. 参数热更新:/sdcard/RealtimeVoice/voice_config.json(复用 M0 配置格式,
|
||||
* 每 2 秒检查一次修改时间;宿主 App 有存储权限,可直接读)
|
||||
* 4. 只做 L1(Java AudioRecord);若微信通话走 AAudio/native 采集(L2/L3),
|
||||
* 需在 M1 验证阶段确认并追加 hook
|
||||
*/
|
||||
public class HookEntry implements IXposedHookLoadPackage {
|
||||
|
||||
private static final String TAG = "[变声M1]";
|
||||
|
||||
/** 注入目标(M2 阶段补 赫兹/他趣 的实测包名) */
|
||||
private static final Set<String> TARGET_PKGS = new HashSet<>(Arrays.asList(
|
||||
"com.tencent.mm", // 微信
|
||||
"com.tencent.mobileqq", // QQ
|
||||
"cn.soulapp.android", // Soul
|
||||
"cn.neoclub.uki" // Uki
|
||||
));
|
||||
|
||||
/**
|
||||
* 配置查找顺序(hook 运行于宿主 UID,Android 11+ 分区存储下 /sdcard 直读可能被拒):
|
||||
* 1. /data/local/tmp —— adb push 可写、全应用可读,联调首选
|
||||
* 2. /sdcard/RealtimeVoice/ —— 兼容旧路径(宿主有存储权限时可用)
|
||||
*/
|
||||
private static final String[] CFG_PATHS = {
|
||||
"/data/local/tmp/voice_config.json",
|
||||
"/sdcard/RealtimeVoice/voice_config.json",
|
||||
};
|
||||
private static volatile long cfgMtimeSeen = 0;
|
||||
private static volatile long cfgLastCheckMs = 0;
|
||||
private static volatile String cfgPathSeen = "";
|
||||
|
||||
@Override
|
||||
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) {
|
||||
if (!TARGET_PKGS.contains(lpparam.packageName)) return;
|
||||
XposedBridge.log(TAG + " 注入目标: " + lpparam.packageName);
|
||||
|
||||
// AudioRecord.read 的常用重载(byte[] / short[],3 参与 4 参版本)
|
||||
hookRead("byte", new Object[]{byte[].class, int.class, int.class});
|
||||
hookRead("byte", new Object[]{byte[].class, int.class, int.class, int.class});
|
||||
hookRead("short", new Object[]{short[].class, int.class, int.class});
|
||||
hookRead("short", new Object[]{short[].class, int.class, int.class, int.class});
|
||||
}
|
||||
|
||||
private void hookRead(final String kind, Object[] paramTypes) {
|
||||
try {
|
||||
Object[] args = Arrays.copyOf(paramTypes, paramTypes.length + 1);
|
||||
args[paramTypes.length] = new XC_MethodHook() {
|
||||
@Override
|
||||
protected void afterHookedMethod(MethodHookParam param) {
|
||||
try {
|
||||
Object result = param.getResult();
|
||||
if (!(result instanceof Integer)) return;
|
||||
int n = (Integer) result;
|
||||
if (n <= 0) return;
|
||||
|
||||
Object buf = param.args[0];
|
||||
AudioRecord rec = (AudioRecord) param.thisObject;
|
||||
|
||||
// 首次/采样率变化时初始化引擎
|
||||
VoiceEngineMin.ensureInit(rec.getSampleRate());
|
||||
maybeReloadConfig();
|
||||
|
||||
if ("byte".equals(kind)) {
|
||||
VoiceEngineMin.nativeProcessByte((byte[]) buf, n);
|
||||
} else {
|
||||
VoiceEngineMin.nativeProcessShort((short[]) buf, n);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
// 绝不让 hook 异常波及宿主 App
|
||||
}
|
||||
}
|
||||
};
|
||||
XposedHelpers.findAndHookMethod(AudioRecord.class, "read", args);
|
||||
} catch (Throwable t) {
|
||||
XposedBridge.log(TAG + " hook read(" + kind + ") 失败: " + t);
|
||||
}
|
||||
}
|
||||
|
||||
/** 配置热更新:每 2 秒查一次文件修改时间,变了才解析下发 */
|
||||
private static void maybeReloadConfig() {
|
||||
try {
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - cfgLastCheckMs < 2000) return;
|
||||
cfgLastCheckMs = now;
|
||||
|
||||
// 依次尝试配置路径,取第一个存在的
|
||||
File f = null;
|
||||
for (String path : CFG_PATHS) {
|
||||
File cand = new File(path);
|
||||
if (cand.exists() && cand.length() > 0) {
|
||||
f = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (f == null) return; // 两个路径都没有 → 用默认参数(静默即可)
|
||||
long mtime = f.lastModified();
|
||||
if (mtime == cfgMtimeSeen) return;
|
||||
|
||||
byte[] buf = new byte[(int) Math.min(f.length(), 65536)];
|
||||
try (FileInputStream in = new FileInputStream(f)) {
|
||||
int off = 0;
|
||||
while (off < buf.length) {
|
||||
int r = in.read(buf, off, buf.length - off);
|
||||
if (r < 0) break;
|
||||
off += r;
|
||||
}
|
||||
JSONObject p = new JSONObject(new String(buf, 0, off, StandardCharsets.UTF_8))
|
||||
.optJSONObject("params");
|
||||
if (p == null) return;
|
||||
|
||||
VoiceEngineMin.nativeSetParams(
|
||||
(float) p.optDouble("pitchSemitones", 9),
|
||||
(float) p.optDouble("formantRatio", 1.20),
|
||||
(float) p.optDouble("strength", 1.0),
|
||||
(float) p.optDouble("eqFreqHz", 3000),
|
||||
(float) p.optDouble("eqGainDb", 3),
|
||||
(float) p.optDouble("gateThreshold", 0.006),
|
||||
(float) p.optDouble("f0MinHz", 65),
|
||||
(float) p.optDouble("f0MaxHz", 500),
|
||||
(float) p.optDouble("smoothing", 0.05),
|
||||
p.optBoolean("bypass", false));
|
||||
VoiceEngineMin.nativeSetTargetMode(
|
||||
p.optBoolean("targetMode", false),
|
||||
(float) p.optDouble("targetF0Hz", 205));
|
||||
cfgMtimeSeen = mtime;
|
||||
if (!f.getAbsolutePath().equals(cfgPathSeen)) {
|
||||
cfgPathSeen = f.getAbsolutePath();
|
||||
XposedBridge.log(TAG + " 配置来源: " + cfgPathSeen);
|
||||
}
|
||||
XposedBridge.log(TAG + " 配置已更新");
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
XposedBridge.log(TAG + " 配置读取异常(路径=" + cfgPathSeen + "): " + t);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.voicecraft.xposed;
|
||||
|
||||
/**
|
||||
* 注入侧引擎包装(轻量版,无 Oboe——音频 I/O 由宿主 App 自己做,
|
||||
* 我们只在 buffer 上就地变声)。native 实现在 engine_min.cpp。
|
||||
*/
|
||||
public final class VoiceEngineMin {
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static int currentSr = 0;
|
||||
|
||||
static {
|
||||
System.loadLibrary("vchangemin");
|
||||
}
|
||||
|
||||
private VoiceEngineMin() {
|
||||
}
|
||||
|
||||
/** 采样率变化时重建引擎(AudioRecord 采样率由宿主决定,常见 16k/44.1k/48k) */
|
||||
public static void ensureInit(int sampleRate) {
|
||||
if (sampleRate == currentSr) return;
|
||||
synchronized (LOCK) {
|
||||
if (sampleRate == currentSr) return;
|
||||
nativeInit(sampleRate);
|
||||
currentSr = sampleRate;
|
||||
}
|
||||
}
|
||||
|
||||
public static native void nativeInit(int sampleRate);
|
||||
|
||||
/**
|
||||
* 全参数下发(与 voice_config.json 一一对应,语义同 M0)
|
||||
*/
|
||||
public static native void nativeSetParams(float pitchSemis, float formant, float strength,
|
||||
float eqFreqHz, float eqGainDb, float gateThreshold,
|
||||
float f0MinHz, float f0MaxHz, float smoothing,
|
||||
boolean bypass);
|
||||
|
||||
/** 目标音高模式:输出 f0 锚定 targetF0Hz(深沉嗓音自动多补) */
|
||||
public static native void nativeSetTargetMode(boolean enabled, float targetF0Hz);
|
||||
|
||||
/**
|
||||
* 就地变声:16 位 PCM 小端(AudioRecord.read(byte[]) 的格式)
|
||||
*
|
||||
* @param nBytes 实际读取的字节数(来自 read 返回值)
|
||||
*/
|
||||
public static native void nativeProcessByte(byte[] buf, int nBytes);
|
||||
|
||||
/**
|
||||
* 就地变声:16 位 PCM(AudioRecord.read(short[]) 的格式)
|
||||
*
|
||||
* @param n 实际读取的样本数(来自 read 返回值)
|
||||
*/
|
||||
public static native void nativeProcessShort(short[] buf, int n);
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
# 实时男变女变声软件 · 设计方案
|
||||
|
||||
> 目标:在微信、QQ、Uki、Soul、赫兹、他趣等应用的**语音通话与语音消息**中实现实时男变女声
|
||||
> 形态:个人自用,Android(root 可用),软件注入方案
|
||||
> 日期:2026-10-30 状态:Phase 2 架构规划(待确认后进入开发)
|
||||
|
||||
---
|
||||
|
||||
## 1. 第一性原理:技术边界(为什么只有两条路)
|
||||
|
||||
Android 音频采集链路:
|
||||
|
||||
```
|
||||
目标App(微信)──> AudioRecord / AAudio ──> AudioFlinger / AAudioService ──> Audio HAL ──> 物理麦克风
|
||||
```
|
||||
|
||||
系统**没有任何第三方 API 允许在链路中间插入处理**(这是安全边界,不是技术选型问题)。因此真·实时注入只有两种实现途径:
|
||||
|
||||
| 途径 | 原理 | 门槛 | 兼容性 |
|
||||
|---|---|---|---|
|
||||
| **A. Root 软件注入** | 在目标 App 进程/音频框架层 hook 采集数据,实时处理后回填 | 手机 root + LSPosed | Android 全 App 通用,iOS 不可行 |
|
||||
| B. 硬件声卡 | USB-C/蓝牙声卡夹在耳机与手机之间,硬件层变声 | 无 | 全平台(含 iOS),需硬件研发 |
|
||||
|
||||
**本方案采用途径 A**(个人自用、手机可 root)。纯软件+免 root 的实时注入不存在;"外放式伪实时"(变声器大师方案)已被否决。
|
||||
|
||||
## 2. 总体架构(三层分离)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ 控制 App(独立 APK,无需 root 能力) │
|
||||
│ 悬浮窗 UI / 预设管理 / per-app 开关 / 强度滑杆 │
|
||||
└───────────────┬─────────────────────────────────┘
|
||||
│ 参数通道(Binder / 本地 Socket + MMKV 配置)
|
||||
┌───────────────▼─────────────────────────────────┐
|
||||
│ 注入模块(LSPosed/Zygisk 模块,运行于目标 App 进程)│
|
||||
│ Hook 层:AudioRecord.read / libaudioclient 采集点 │
|
||||
└───────────────┬─────────────────────────────────┘
|
||||
│ 进程内调用
|
||||
┌───────────────▼─────────────────────────────────┐
|
||||
│ DSP 变声引擎(独立 native .so,纯 C++) │
|
||||
│ 实时管线:VAD → 变调 → 共振峰偏移 → EQ → 输出 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
解耦原则:DSP 引擎不依赖注入方式(可先用测试 App 验证音质);注入模块不含算法(只做数据搬运);UI 与引擎进程隔离(目标 App 崩溃不影响控制端)。
|
||||
|
||||
## 3. 详细设计
|
||||
|
||||
### 3.1 DSP 引擎(核心,先于一切开发)
|
||||
|
||||
**音频管线**(帧长 10ms,采样率自适应 16kHz/48kHz):
|
||||
|
||||
```
|
||||
输入 buffer → 噪声门/VAD → 基频检测(YIN/自相关)
|
||||
→ 变调(PSOLA/WSOLA) → 共振峰偏移(VTLP) → EQ → (可选轻混响/气声) → 输出 buffer
|
||||
```
|
||||
|
||||
**男变女的关键参数**(借鉴变声器大师"预设=参数组合"的思路):
|
||||
|
||||
| 参数 | 男声基准 | 女声目标 | 作用 |
|
||||
|---|---|---|---|
|
||||
| 基频 f0 | 100~140 Hz | 200~240 Hz(+8~+12 半音) | 音高 |
|
||||
| **共振峰偏移(VTLP)** | 1.0 | **1.15~1.25**(声道长度缩放) | **决定"像女人"而非"像小黄人"** |
|
||||
| 高频增益 | 平坦 | 2~4 kHz shelf +3dB | 亮度/柔和度 |
|
||||
| 气声合成 | 无 | 轻度 | 自然度 |
|
||||
|
||||
> 教学要点:**纯升调 = 小黄人/卡通音;共振峰随音高同步搬移(VTLP)= 真实女声**。这是变声器大师那些预设(萝莉/女声1)与"搞怪"类预设的本质区别。预设即参数集:少女(+9st, 1.20)、御姐(+7st, 1.15)、萝莉(+12st, 1.25)。
|
||||
|
||||
**性能预算**:
|
||||
|
||||
| 指标 | 目标 | 说明 |
|
||||
|---|---|---|
|
||||
| 端到端延迟 | < 30 ms | 通话可用(2×10ms buffer + 算法 <10ms) |
|
||||
| CPU 占用 | < 8% 单核 | 骁龙 865 实测为准 |
|
||||
| 音质底线 | 不带"电音/卡通感" | 男女可辨识度 > 90%(听测) |
|
||||
|
||||
**技术选型(避开授权坑)**:
|
||||
|
||||
| 组件 | 选型 | 授权 | 备注 |
|
||||
|---|---|---|---|
|
||||
| 低延迟采集/播放 | **Oboe**(Google) | Apache-2.0 | 不用 FMOD(商用收费,变声器大师用它但要付费) |
|
||||
| 变调 | **SoundTouch**(WSOLA)或自研 PSOLA | LGPL / 自研无限制 | 自研 PSOLA 代码量约 300 行,推荐自研避免传染性授权 |
|
||||
| 共振峰 | 自研 VTLP(线性预测搬移) | 无 | 核心差异化点 |
|
||||
| 框架语言 | C++17 + JNI 薄壳 | — | 引擎独立 .so,可单测 |
|
||||
|
||||
### 3.2 注入层(Root 注入,分层 Hook 策略)
|
||||
|
||||
各 App 音频链路不统一,需**分层覆盖**(这是本方案最大的工程不确定性,M1 里程碑先验证):
|
||||
|
||||
| 层级 | Hook 点 | 覆盖场景 | 工具 |
|
||||
|---|---|---|---|
|
||||
| L1 Java 层 | `android.media.AudioRecord.read()` 全部重载 | 多数 App 的语音消息录制 | LSPosed(Xposed API) |
|
||||
| L2 Native 层 | `libaudioclient.so` → `AudioRecord::read`(PLT/inline hook) | 微信/QQ VoIP(WebRTC 自建音频层直调此函数) | ShadowHook / Dobby |
|
||||
| L3 AAudio 层 | `libaaudio.so` 采集回调(AAudio MMAP 旁路 AudioFlinger) | 新版 App 低延迟采集 | ShadowHook(POC 后按需) |
|
||||
|
||||
实现要点:
|
||||
- **模块形态**:Zygisk(Magisk)+ LSPosed 组合;作用域限定目标 App 包名(微信 `com.tencent.mm`、QQ `com.tencent.mobileqq`、Soul `cn.soulapp.android`,Uki/赫兹/他趣包名 POC 阶段用 adb 确认,不猜)
|
||||
- **处理位置**:在 hook 的 read 返回前对 buffer 就地处理(零拷贝),不改 buffer 尺寸,不破 App 自身逻辑
|
||||
- **参数下发**:控制 App → MMKV/本地 Socket → 注入模块热更新参数(免重启目标 App)
|
||||
- **Root 隐藏**:Shamiko(微信/QQ 有 root/Xposed 风控检测);自用需接受残余封号风险
|
||||
- **保命设计**:总开关 + 单 App 开关 + 异常时旁路直通(bypass),引擎处理耗时超预算自动跳过本帧,绝不卡通话
|
||||
|
||||
### 3.3 控制 UI 层
|
||||
|
||||
- **形态**:悬浮窗(`SYSTEM_ALERT_WINDOW`)+ 常驻通知;无障碍服务保活
|
||||
- **功能**:预设切换(少女/御姐/萝莉/中性女)、强度滑杆(0~100% 混合干湿比)、per-app 生效开关、实时试听、一键直通
|
||||
- **交互借鉴**:变声器大师的悬浮球+语音包列表(快捷切换预设),但砍掉广告/VIP/分享等杂项
|
||||
|
||||
### 3.4 可选升级:神经网络音色(M3)
|
||||
|
||||
经典 DSP 延迟低但"像女声"上限有限。高拟真路线:
|
||||
- **RVC-lite(ONNX 量化 int8)** 做音色转换,骁龙 865 走 NNAPI/QNN GPU 推理,延迟 150~400ms
|
||||
- **双模**:通话用经典 DSP(低延迟);语音消息离线处理用神经网络(高拟真,录制完再转,无延迟约束)
|
||||
- 训练数据可用公开女声语料(合规来源),男→女平行数据少,可用 any-to-any 转换模型
|
||||
|
||||
## 4. 里程碑
|
||||
|
||||
| 阶段 | 内容 | 周期 | 验收标准 |
|
||||
|---|---|---|---|
|
||||
| **M0 引擎原型** | DSP 引擎 + 独立测试 App(录音→实时变声→播放);**无需 root,当前手机即可测** | 1~2 周 | 女声听感达标、延迟 <30ms、CPU <8% |
|
||||
| **M1 注入 POC** | root 手机,LSPosed 模块打通微信语音消息 + 语音通话 | 1~2 周 | 微信内通话对方听到女声 |
|
||||
| **M2 多 App 适配** | QQ/Soul/Uki/赫兹/他趣 逐 App 验证 hook 点;悬浮窗 UI;预设调优 | 2~3 周 | 目标 App 清单全通过 |
|
||||
| **M3 音色升级(可选)** | 神经网络双模 + 硬件路线评估 | 另行 | 语音消息达到"以假乱真" |
|
||||
|
||||
## 5. 风险与应对
|
||||
|
||||
| 风险 | 等级 | 应对 |
|
||||
|---|---|---|
|
||||
| 微信/QQ root/Xposed 风控 | 高 | Shamiko + 作用域最小化;自用自担封号风险(提示:主号慎用) |
|
||||
| AAudio MMAP 旁路导致 L1/L2 hook 失效 | 中 | M1 先验证微信实际链路,失效则补 L3 |
|
||||
| 蓝牙耳机带来额外 100~200ms 延迟 | 中 | 调试用有线/外放;蓝牙场景做延迟补偿 |
|
||||
| 通话链路降噪/AEC 与变声互相干扰 | 中 | 处理点放在 AEC 之后(hook read 拿到的已是处理后数据,天然满足) |
|
||||
| iOS 用户 | — | 本方案不覆盖,仅硬件路线可解(列为 M3 评估项) |
|
||||
| 合规 | — | **仅限个人娱乐;禁止用于欺诈、冒充、骚扰等违法用途**。变声 ≠ 匿名保护,违法行为可追溯 |
|
||||
|
||||
## 6. 与变声器大师的关系:借鉴 vs 不复刻
|
||||
|
||||
| 借鉴 | 不复刻 |
|
||||
|---|---|
|
||||
| "预设 = DSP 参数组合"的产品抽象(萝莉/大叔/女声1) | FMOD 引擎(商用授权费)→ 改用 Oboe + 自研 DSP |
|
||||
| 悬浮窗 + 预设快捷切换的交互 | 文件进文件出的批处理架构 → 改为实时流式 |
|
||||
| 变声参数维度(音调/速度/特效) | 乐固加固、广告 SDK 大杂烩(自用项目不需要) |
|
||||
| — | 伪实时外放方案(不满足"真·实时"要求) |
|
||||
|
||||
---
|
||||
|
||||
*下一步:确认本方案后进入 M0(DSP 引擎开发),产物落盘 D:\voiceScript。*
|
||||
@@ -0,0 +1,134 @@
|
||||
# 变声器大师(com.xinmang.voicechanger v6.4.2)逆向分析报告
|
||||
|
||||
> 分析日期:2026-10-30
|
||||
> 样本来源:本机连接的 iQOO Neo3(V1981A,Android 12)已安装应用
|
||||
> 样本文件:`com.xinmang.voicechanger-6.4.2.apk`(110.2 MB,versionCode 680)
|
||||
> 分析产物:`decompiled\`(jadx 反编译输出)、`native\`(提取的原生库与加密 dex)
|
||||
|
||||
---
|
||||
|
||||
## 1. 应用身份
|
||||
|
||||
| 项目 | 值 |
|
||||
|---|---|
|
||||
| 应用名 | 变声器大师 |
|
||||
| 包名 | com.xinmang.voicechanger |
|
||||
| 开发商 | 深圳新曼(xinmang) |
|
||||
| 版本 | 6.4.2(versionCode 680,minSdk 24 / targetSdk 31) |
|
||||
| 安装来源 | vivo 应用商店(com.bbk.appstore) |
|
||||
| 启动入口 | `.activity.SplashAdActivity`(闪屏广告页) |
|
||||
|
||||
## 2. 保护方案:腾讯乐固(Legu)4.6.2.2
|
||||
|
||||
**已验证事实:**
|
||||
|
||||
- 7 个 dex 合计仅约 83 KB(classes.dex 69 KB + classes2~7.dex 各 2.4 KB),远小于正常体量 → **壳 dex**,业务代码不在此
|
||||
- 壳 dex 内容:`com.wrapper.proxyapplication.*`(乐固标准代理加载器)、`com.xinmang.voicechanger.MyWrapperProxyApplication`(壳 Application 入口)、`com.example.helloworld`(乐固模板残留)
|
||||
- 真实业务 dex 藏于 `assets/0OO00l111l1l`(25.86 MB,混淆文件名)
|
||||
- 壳 native 库:`libshella-4.6.2.2.so`(乐固脱壳器)、`libshell-super.com.xinmang.voicechanger.so`、`libanti_break_debug.so`(反调试)
|
||||
- 加载流程(来自 `MyWrapperProxyApplication.initProxyApplication()`):
|
||||
`Util.PrepareSecurefiles(ctx, apkzf)` 解出受保护文件 → `System.loadLibrary(libshella)` → 内存中解密 dex 并接管 ClassLoader
|
||||
|
||||
**加密 dex 取证结论:**
|
||||
|
||||
- 头部含"裸露"的 dex magic(`dex\n` + 插入垃圾字节 `0xff` + `037\0`)与 endian 标志(`78 56 34` + 插入 `0xb1` + `12`)→ 头字段有**插字节混淆**
|
||||
- 主体 25MB 全部为高熵数据(各块 64KB 采样字节多样性 256/256),无任何明文类名字符串(`com/xinmang`、`Landroid`、`Lcom/` 等均未命中)→ **整体加密,非仅头部损坏**
|
||||
- 结论:静态解密需逆向 `libshella-4.6.2.2.so` 的解密算法,或运行时内存脱壳(需 root/frida,本机未 root 不可行)
|
||||
|
||||
## 3. 核心成果:变声实现机制(native 层,已完整还原)
|
||||
|
||||
变声核心是 **`libchangeSound.so`(0.23 MB)+ FMOD 音频引擎(libfmod.so / libfmodL.so,FMOD 5.x)**,算法在 native 层,**不受 dex 加壳影响**。
|
||||
|
||||
### 3.1 JNI 接口(Java ↔ native 边界)
|
||||
|
||||
Java 入口类:`com.xinmang.voicechanger.FMODUtils` 与 `com.xinmang.voicechanger.utils.FMODUtils`
|
||||
|
||||
| JNI 函数 | 功能推断(依据字符串语义) |
|
||||
|---|---|
|
||||
| `changeVoiceFile` / `changeVoiceWithFile` | 变声主入口:对音频文件施加变声 |
|
||||
| `playSoundWithParameter` | 按参数实时播放变声效果(试听) |
|
||||
| `customParameter` / `customParameterSave` | 自定义变声参数调节与保存 |
|
||||
| `audioWriteToFile` / `audioCusWriteToFile` | 变声结果导出为音频文件 |
|
||||
| `audioPause` / `isPlaying` / `stateStart` / `stateStop` | 播放控制 |
|
||||
|
||||
### 3.2 底层引擎用法(FMOD C++ API 符号导出)
|
||||
|
||||
| FMOD API | 作用 |
|
||||
|---|---|
|
||||
| `System::createSound` / `playSound` | 加载与播放音频 |
|
||||
| `Channel::setFrequency` / `getFrequency` | **改变播放采样频率 → 变速变调(磁带式 pitch 效果)** |
|
||||
| `System::createDSPByType(FMOD_DSP_TYPE)` | **按类型创建 DSP 效果器(变声特效链)** |
|
||||
| `DSP::setParameterFloat` / `setParameterInt` | 调节 DSP 参数(音调/回声/混响等) |
|
||||
| `ChannelControl::addDSP` | 将 DSP 挂到声道(效果链组合) |
|
||||
| `ChannelControl::setVolume` / `mixerSuspend` / `mixerResume` / `setOutput` | 音量、混音器控制、输出切换 |
|
||||
|
||||
**机制总结(推断,依据充分):**
|
||||
变声 = FMOD DSP 链式处理。两条技术路线并存:
|
||||
1. **变调不变速**:`FMOD_DSP_TYPE_PITCHSHIFT`(音高偏移 DSP)
|
||||
2. **变速变调**:`Channel::setFrequency` 改变播放频率(升降调的同时改变速度)
|
||||
|
||||
"萝莉/大叔/小黄人"等预设即不同 DSP 参数组合(pitch 值 + 频率系数 + 特效叠加),预设参数表在加密 dex 的 Java 层(`FMODUtils` 的 Java 包装),暂未取得。
|
||||
|
||||
### 3.3 音频编解码辅助
|
||||
|
||||
- `libmp3lame.so` / `liblamejni.so`:LAME MP3 编码(变声结果导出 MP3)
|
||||
- `librxffmpeg-core.so`(15.8 MB)/ `rxffmpeg-player` / `rxffmpeg-invoke`:RxFFmpeg 音视频处理(格式转换/裁剪)
|
||||
|
||||
## 4. 功能地图(资源层 + 组件层推断)
|
||||
|
||||
变声预设(strings.xml 明文,key → 中文):
|
||||
`Lorie→萝莉`、`uncle→大叔`、`minion→小黄人`、`empty→空灵`、`funny→搞怪`、`girl→女声1`(更多预设硬编码于加密 dex,未取得)
|
||||
|
||||
| 功能模块 | 证据(布局/字符串) |
|
||||
|---|---|
|
||||
| 录音变声 | `activity_new_record`、`dialog_home_recode`、"点击录音/重新录音" |
|
||||
| 音频文件变声 | `activity_choose_audio`、`activity_audio_change` |
|
||||
| **文字变声(TTS)** | `activity_text_voice`、`fragment_text_voice`、"文字变声功能需要…管理保存变声后的文件" |
|
||||
| 合成/混音 | `activity_combined_sound`、`dialog_mix_sound`、`fragment_new_combined_sound` |
|
||||
| **游戏变声悬浮窗** | `activity_game_explan`、`activity_help_game`、`activity_help_window`、`float_window_small`、`float_window_record_menu`、悬浮按钮帮助文案(vivo/小米/华为适配说明) |
|
||||
| 语音包 | `activity_voice_package`、`adapter_window_voice_package` |
|
||||
| 变声收藏 | `activity_voice_favor` |
|
||||
| 我的语音(文件管理) | `activity_my_record`、"我的语音功能需要使用文件存储权限" |
|
||||
| VIP 内购 | `activity_main_buy`、`activity_share_vip_page` |
|
||||
| 分享/登录 | `dialog_share`、微信/QQ 登录(`wm_wx_*` / `wm_qq_*`)、`com.tencent.tauth.AuthActivity` |
|
||||
|
||||
## 5. 三方 SDK 盘点(native 库 + 组件推断)
|
||||
|
||||
| 类别 | SDK | 证据 |
|
||||
|---|---|---|
|
||||
| 语音识别/合成 | 百度语音(libmsc/libBaiduSpeechSDK/libbd_etts/libbdtts 等) | TTS 语音数据 assets |
|
||||
| 语音交互 | 阿里云智能语音(libalibabacloud-idst-speech.so 3.3MB) | so |
|
||||
| 广告-穿山甲 | libtt_* / libPglbizssdk_ml / libtobEmbedEncrypt / libavmdl_lite | so + `CSJIndependentProcessDownloadService` |
|
||||
| 广告-快手 | kwad SDK | `com.kwad.sdk.api.proxy.app.*` |
|
||||
| 广告-百度 | bdxadsdk.jar(assets) | so + jar |
|
||||
| 广告-广点通 | gdtadv2.jar(assets/gdt_plugin) | jar |
|
||||
| 统计 | 华为 HiAnalytics、腾讯 | components |
|
||||
| 工具 | okhttp3、litepal(数据库)、blankj utilcode、glide-webp、pl-droidsonroids-gif(动图)、lottie | so + assets |
|
||||
| 其他 | `co.tinode.tindroid.MessageActivity`(Tinode IM SDK,用途待查) | components |
|
||||
|
||||
## 6. 结论可信度分级
|
||||
|
||||
**已验证(静态证据直接支撑):**
|
||||
- 壳方案为腾讯乐固 4.6.2.2,业务 dex 整体加密于 `assets/0OO00l111l1l`
|
||||
- 变声核心在 native:libchangeSound.so JNI 接口 + FMOD 引擎
|
||||
- 变声机制为 FMOD DSP 链(setFrequency 变调 + createDSPByType 特效)
|
||||
- 功能清单(录音/文件/文字变声、游戏悬浮窗、语音包、VIP)
|
||||
|
||||
**推断(依据充分但非直接证据):**
|
||||
- 各预设(萝莉/大叔等)= DSP 参数组合(参数表在加密 dex)
|
||||
- `changeVoiceFile` 等方法的精确参数语义(JNI 名称+FMOD 用法推断)
|
||||
|
||||
**未知(受阻于加固):**
|
||||
- 业务 Java 层实现细节:预设参数值、UI 流程逻辑
|
||||
- 网络接口(服务器 API、数据上报行为)
|
||||
- 文字变声调用的是百度还是阿里云 TTS
|
||||
|
||||
## 7. 后续建议
|
||||
|
||||
1. **取参数表**:对 `libchangeSound.so` 做反汇编(Ghidra/IDA/REA native provider),还原 JNI 函数内 DSP 类型与参数索引映射,即可复刻变声效果
|
||||
2. **脱壳**(可选,重量级):逆向 `libshella-4.6.2.2.so` 解密函数还原 `0OO00l111l1l`,或 root 设备后 frida 内存 dump dex
|
||||
3. **接口抓包**:手机设代理抓 HTTPS(需过证书校验),取得服务器 API
|
||||
4. **复刻验证**:用 FMOD(或 fmod 开源替代)按 §3.2 的 DSP 链实现原型,对照 app 预设听感校准参数
|
||||
|
||||
---
|
||||
*分析工具:adb、jadx 1.5.6(D:\tmp\re-tools\jadx-cli)、PowerShell 字节取证。所有产物位于 D:\voiceScript。*
|
||||
Reference in New Issue
Block a user