feat: 初始化变声器项目仓库(逆向分析 + 实时变声 + PC 变声麦)
包含三大模块: - 逆向分析报告与实时变声方案设计文档 - realtime-voice:Android 实时变声(PSOLA 变调 + VTLP 共振峰 DSP 管线、Xposed 注入模块) - pc-voice:PC 变声麦工具(miniaudio 引擎、可配置 DSP 参数) 已通过 .gitignore 排除构建产物、本机工具链与本机路径配置。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1,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>
|
||||
Reference in New Issue
Block a user