初始化 TTS 引擎工程:Android 系统引擎、Go 在线合成服务与测试客户端

- android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热
- server:Go CPU 合成服务与部署文件
- test-client:端到端验证客户端
- 模型与语音包不入库,见 models/README.md
This commit is contained in:
tongtong committed 2026-11-23 14:59:46 +08:00
commit 1856de97bc
62 files changed
+3787

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
plugins {
id 'com.android.application'
}
android {
namespace 'com.ttstd.tts.engine'
compileSdk 37
defaultConfig {
applicationId 'com.ttstd.tts.engine'
minSdk 23
targetSdk 37
versionCode 1
versionName '0.1.0'
ndk {
abiFilters 'arm64-v8a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
lint {
abortOnError false
checkReleaseBuilds = false
}
}
dependencies {
implementation files('libs/sherpa-onnx-2.0.1.aar')
implementation 'org.jetbrains.kotlin:kotlin-stdlib:2.4.21'
}
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
-keep class com.k2fsa.sherpa.onnx.** { *; }
-keepclassmembers class kotlin.jvm.functions.** { *; }
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="false"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/EngineTheme">
<service
android:name=".TtsEngineService"
android:exported="true"
android:permission="android.permission.BIND_TTS_SERVICE">
<intent-filter>
<action android:name="android.intent.action.TTS_SERVICE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.speech.tts"
android:resource="@xml/tts_engine" />
</service>
<activity
android:name=".SettingsActivity"
android:exported="true"
android:label="@string/settings_title">
<intent-filter>
<action android:name="com.android.settings.TTS_SETTINGS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".CheckVoiceDataActivity"
android:exported="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.speech.tts.engine.CHECK_TTS_DATA" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".GetSampleTextActivity"
android:exported="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.speech.tts.engine.GET_SAMPLE_TEXT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,47 @@
package com.ttstd.tts.engine;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.ArrayList;
import java.util.Locale;
import java.util.MissingResourceException;
public class CheckVoiceDataActivity extends Activity {
private static final String TAG = "TtsCheckVoiceData";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> available = new ArrayList<>();
for (VoicePack pack : VoiceRepository.get(this).all()) {
available.add(iso3(pack));
}
Log.i(TAG, "checkFor=" + getIntent().getStringExtra(TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR)
+ " available=" + available);
Intent data = new Intent();
data.putStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES, available);
setResult(RESULT_OK, data);
finish();
}
private static String iso3(VoicePack pack) {
Locale locale = pack.locale();
String language;
String country;
try {
language = locale.getISO3Language();
} catch (MissingResourceException e) {
language = locale.getLanguage();
}
try {
country = locale.getISO3Country();
} catch (MissingResourceException e) {
country = locale.getCountry();
}
return language + "-" + country;
}
}
@@ -0,0 +1,17 @@
package com.ttstd.tts.engine;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
public class GetSampleTextActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent data = new Intent();
data.putExtra(TextToSpeech.Engine.EXTRA_SAMPLE_TEXT, getString(R.string.settings_sample));
setResult(RESULT_OK, data);
finish();
}
}
@@ -0,0 +1,26 @@
package com.ttstd.tts.engine;
import android.speech.tts.SynthesisCallback;
final class PcmWriter {
private PcmWriter() {
}
static boolean write(SynthesisCallback callback, float[] samples, int sampleRate) {
int maxSamples = Math.max(1, sampleRate / 50);
for (int from = 0; from < samples.length; from += maxSamples) {
int len = Math.min(maxSamples, samples.length - from);
byte[] pcm = new byte[len * 2];
for (int i = 0; i < len; i++) {
float v = samples[from + i];
if (v > 1f) v = 1f;
if (v < -1f) v = -1f;
int s = Math.round(v * 32767f);
pcm[i * 2] = (byte) s;
pcm[i * 2 + 1] = (byte) (s >> 8);
}
if (callback.audioAvailable(pcm, 0, pcm.length) != 0) return false;
}
return true;
}
}
@@ -0,0 +1,80 @@
package com.ttstd.tts.engine;
/**
* Pitch shift without changing duration: time-stretch by the pitch factor, then resample by it.
* The server must use the same algorithm and parameters to keep output consistent.
*/
final class PitchShifter {
private static final int GRAIN = 1024;
private static final int OVERLAP = 512;
private static final int HOP_S = GRAIN - OVERLAP;
private static final int SEARCH = 128;
private PitchShifter() {
}
static float[] shift(float[] samples, float factor) {
if (samples.length == 0 || Math.abs(factor - 1f) < 0.01f) return samples;
float[] stretched = timeStretch(samples, factor);
return resample(stretched, factor);
}
private static float[] timeStretch(float[] in, float factor) {
int hopA = Math.max(1, Math.round(HOP_S / factor));
float[] window = hann(GRAIN);
int expected = Math.max(GRAIN, Math.round(in.length * factor));
float[] out = new float[expected + GRAIN];
int inPos = 0;
int outPos = 0;
while (inPos + GRAIN <= in.length) {
int best = inPos;
if (outPos > 0) {
int from = Math.max(0, inPos - SEARCH);
int to = Math.min(in.length - GRAIN, inPos + SEARCH);
double bestCorr = -1;
for (int cand = from; cand <= to; cand += 4) {
double corr = 0;
for (int i = 0; i < OVERLAP; i++) {
corr += (double) in[cand + i] * out[outPos + i];
}
if (corr > bestCorr) {
bestCorr = corr;
best = cand;
}
}
}
for (int i = 0; i < GRAIN; i++) {
out[outPos + i] += in[best + i] * window[i];
}
inPos += hopA;
outPos += HOP_S;
}
float[] result = new float[expected];
System.arraycopy(out, 0, result, 0, Math.min(expected, out.length));
return result;
}
private static float[] resample(float[] in, float factor) {
int outLen = Math.max(1, Math.round(in.length / factor));
float[] out = new float[outLen];
for (int i = 0; i < outLen; i++) {
double pos = i * (double) factor;
int i0 = (int) pos;
if (i0 >= in.length) break;
int i1 = Math.min(i0 + 1, in.length - 1);
double frac = pos - i0;
out[i] = (float) (in[i0] * (1 - frac) + in[i1] * frac);
}
return out;
}
private static float[] hann(int size) {
float[] w = new float[size];
for (int i = 0; i < size; i++) {
w[i] = (float) (0.5 - 0.5 * Math.cos(2 * Math.PI * i / (size - 1)));
}
return w;
}
}
@@ -0,0 +1,238 @@
package com.ttstd.tts.engine;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.speech.tts.TextToSpeech;
import android.speech.tts.Voice;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
public class SettingsActivity extends Activity {
private static final String TAG = "TtsEngineSettings";
private static final String ENGINE = "com.ttstd.tts.engine";
private static final int REQUEST_IMPORT = 1001;
private RadioGroup group;
private TextView info;
private TextView status;
private Button importButton;
private Button deleteButton;
private TextToSpeech preview;
private VoiceRepository repository;
private String selected = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.settings_title);
setContentView(R.layout.activity_settings);
group = findViewById(R.id.voice_group);
info = findViewById(R.id.voice_info);
status = findViewById(R.id.import_status);
importButton = findViewById(R.id.btn_import);
deleteButton = findViewById(R.id.btn_delete);
repository = VoiceRepository.get(this);
repository.reload();
rebuild();
importButton.setOnClickListener(v -> importPack());
deleteButton.setOnClickListener(v -> confirmDelete());
findViewById(R.id.btn_preview).setOnClickListener(v -> preview());
initPreview();
}
private void rebuild() {
group.setOnCheckedChangeListener(null);
group.removeAllViews();
List<VoicePack> packs = repository.all();
VoicePack current = repository.getDefault();
selected = current != null ? current.name : "";
for (VoicePack pack : packs) {
RadioButton radio = new RadioButton(this);
radio.setText(pack.label + "(" + pack.localeTag + ")");
radio.setId(View.generateViewId());
radio.setTag(pack.name);
group.addView(radio);
if (pack.name.equals(selected)) group.check(radio.getId());
}
info.setVisibility(packs.isEmpty() ? TextView.VISIBLE : TextView.GONE);
if (packs.isEmpty()) info.setText(R.string.settings_empty);
group.setOnCheckedChangeListener((g, checkedId) -> {
RadioButton radio = g.findViewById(checkedId);
if (radio == null) return;
selected = String.valueOf(radio.getTag());
getSharedPreferences(VoiceRepository.PREFS, MODE_PRIVATE)
.edit().putString(VoiceRepository.KEY_DEFAULT_VOICE, selected).apply();
updateActions();
});
updateActions();
}
private void updateActions() {
VoicePack pack = repository.get(selected);
deleteButton.setEnabled(pack != null && repository.isUserPack(pack));
}
private void importPack() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(intent, REQUEST_IMPORT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != REQUEST_IMPORT || resultCode != RESULT_OK
|| data == null || data.getData() == null) return;
Uri treeUri = data.getData();
importButton.setEnabled(false);
deleteButton.setEnabled(false);
status.setText(R.string.settings_importing);
new Thread(() -> doImport(treeUri), "tts-import").start();
}
private void doImport(Uri treeUri) {
File dest = new File(VoiceRepository.userDir(this), "import-" + System.currentTimeMillis());
String message;
try {
if (!dest.mkdirs() && !dest.isDirectory()) throw new IOException("mkdir " + dest);
copyDocument(treeUri, DocumentsContract.getTreeDocumentId(treeUri), dest);
int count = VoiceRepository.validate(dest);
if (count > 0) {
repository.reload();
message = getString(R.string.settings_import_ok, count);
} else {
deleteTree(dest);
message = getString(count == VoiceRepository.INVALID_HASH
? R.string.settings_import_hash : R.string.settings_import_fail);
}
} catch (Exception e) {
Log.e(TAG, "import failed", e);
deleteTree(dest);
message = getString(R.string.settings_import_fail);
}
String text = message;
runOnUiThread(() -> {
status.setText(text);
importButton.setEnabled(true);
rebuild();
initPreview();
});
}
private void copyDocument(Uri treeUri, String documentId, File dest) throws IOException {
Uri children = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, documentId);
String[] projection = {
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
};
try (Cursor cursor = getContentResolver().query(children, projection, null, null, null)) {
if (cursor == null) throw new IOException("query " + children);
while (cursor.moveToNext()) {
String childId = cursor.getString(0);
String name = cursor.getString(1);
String mime = cursor.getString(2);
if (name == null || name.contains("/") || name.contains("\\")
|| name.equals(".") || name.equals("..")) {
throw new IOException("bad entry name: " + name);
}
File child = new File(dest, name);
if (DocumentsContract.Document.MIME_TYPE_DIR.equals(mime)) {
if (!child.mkdirs() && !child.isDirectory()) throw new IOException("mkdir " + child);
copyDocument(treeUri, childId, child);
} else {
Uri source = DocumentsContract.buildDocumentUriUsingTree(treeUri, childId);
try (InputStream in = getContentResolver().openInputStream(source);
FileOutputStream out = new FileOutputStream(child)) {
if (in == null) throw new IOException("open " + source);
byte[] buf = new byte[64 * 1024];
int n;
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
}
}
}
}
}
private void confirmDelete() {
VoicePack pack = repository.get(selected);
if (pack == null) return;
if (!repository.isUserPack(pack)) {
status.setText(R.string.settings_delete_builtin);
return;
}
new AlertDialog.Builder(this)
.setMessage(getString(R.string.settings_delete_confirm, pack.label))
.setPositiveButton(android.R.string.ok, (d, w) -> {
if (repository.deleteUserPack(pack)) {
status.setText(R.string.settings_deleted);
rebuild();
initPreview();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private static void deleteTree(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) for (File child : children) deleteTree(child);
}
file.delete();
}
private void initPreview() {
if (preview != null) {
preview.shutdown();
preview = null;
}
preview = new TextToSpeech(this, status -> {
if (status != TextToSpeech.SUCCESS) Log.e(TAG, "preview engine init failed: " + status);
}, ENGINE);
}
private void preview() {
if (preview == null || selected.isEmpty()) return;
Set<Voice> voices = preview.getVoices();
if (voices != null) {
for (Voice voice : voices) {
if (voice.getName().equals(selected)) {
preview.setVoice(voice);
break;
}
}
}
int result = preview.speak(getString(R.string.settings_sample),
TextToSpeech.QUEUE_FLUSH, null, "preview");
if (result != TextToSpeech.SUCCESS) Log.e(TAG, "preview speak failed: " + result);
}
@Override
protected void onDestroy() {
if (preview != null) {
preview.stop();
preview.shutdown();
preview = null;
}
super.onDestroy();
}
}
@@ -0,0 +1,146 @@
package com.ttstd.tts.engine;
import android.speech.tts.SynthesisCallback;
import android.util.Log;
import com.k2fsa.sherpa.onnx.GenerationConfig;
import com.k2fsa.sherpa.onnx.OfflineTts;
import com.k2fsa.sherpa.onnx.OfflineTtsConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsKittenModelConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsKokoroModelConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsMatchaModelConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsModelConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsPocketModelConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsSupertonicModelConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsVitsModelConfig;
import com.k2fsa.sherpa.onnx.OfflineTtsZipVoiceModelConfig;
import java.util.ArrayList;
import java.util.List;
import kotlin.jvm.functions.Function1;
final class Synthesizer {
interface StopSignal {
boolean stopped();
}
private static final String TAG = "TtsSynthesizer";
private OfflineTts tts;
private String loadedModel;
Synthesizer() {
}
synchronized int sampleRate(VoicePack pack) {
return obtain(pack).sampleRate();
}
void warmUp(VoicePack pack) {
synchronized (this) {
obtain(pack);
long start = System.currentTimeMillis();
GenerationConfig gen = new GenerationConfig(0.2f, 1f, pack.speakerId,
null, 0, null, 5, null, null, null);
tts.generateWithConfigAndCallback("你好", gen, new Function1<float[], Integer>() {
@Override
public Integer invoke(float[] samples) {
return 1;
}
});
Log.i(TAG, "warmup done in " + (System.currentTimeMillis() - start) + " ms");
}
}
synchronized void synthesize(VoicePack pack, String text, float speed, float pitch,
SynthesisCallback callback, StopSignal stop) {
OfflineTts engine = obtain(pack);
final int sampleRate = engine.sampleRate();
final boolean shift = Math.abs(pitch - 1f) >= 0.01f;
final List<float[]> pending = shift ? new ArrayList<>() : null;
final boolean[] aborted = {false};
GenerationConfig gen = new GenerationConfig(0.2f, speed, pack.speakerId,
null, 0, null, 5, null, null, null);
engine.generateWithConfigAndCallback(text, gen, new Function1<float[], Integer>() {
@Override
public Integer invoke(float[] samples) {
if (stop.stopped()) {
aborted[0] = true;
return 0;
}
if (shift) {
pending.add(samples);
return 1;
}
if (!PcmWriter.write(callback, samples, sampleRate)) {
aborted[0] = true;
return 0;
}
return 1;
}
});
if (shift && !aborted[0]) {
float[] shifted = PitchShifter.shift(concat(pending), pitch);
PcmWriter.write(callback, shifted, sampleRate);
}
}
synchronized void release() {
releaseLocked();
}
private OfflineTts obtain(VoicePack pack) {
if (tts != null && pack.modelPath.equals(loadedModel)) return tts;
releaseLocked();
OfflineTtsVitsModelConfig vits = new OfflineTtsVitsModelConfig();
vits.setModel(pack.modelPath);
vits.setTokens(pack.tokensPath);
if (!pack.lexiconPath.isEmpty()) vits.setLexicon(pack.lexiconPath);
vits.setDataDir(pack.dataDir);
OfflineTtsModelConfig model = new OfflineTtsModelConfig(
vits,
new OfflineTtsMatchaModelConfig(),
new OfflineTtsKokoroModelConfig(),
new OfflineTtsZipVoiceModelConfig(),
new OfflineTtsKittenModelConfig(),
new OfflineTtsPocketModelConfig(),
new OfflineTtsSupertonicModelConfig(),
2, false, "cpu");
OfflineTtsConfig config = new OfflineTtsConfig(model, pack.ruleFsts, "", 1, 0.2f);
long start = System.currentTimeMillis();
tts = new OfflineTts(null, config);
loadedModel = pack.modelPath;
Log.i(TAG, "loaded " + pack.name + " in " + (System.currentTimeMillis() - start) + " ms");
return tts;
}
private void releaseLocked() {
if (tts != null) {
try {
tts.release();
} catch (Throwable t) {
Log.w(TAG, "release failed", t);
}
}
tts = null;
loadedModel = null;
}
private static float[] concat(List<float[]> chunks) {
int total = 0;
for (float[] chunk : chunks) total += chunk.length;
float[] out = new float[total];
int offset = 0;
for (float[] chunk : chunks) {
System.arraycopy(chunk, 0, out, offset, chunk.length);
offset += chunk.length;
}
return out;
}
}
@@ -0,0 +1,139 @@
package com.ttstd.tts.engine;
import android.media.AudioFormat;
import android.speech.tts.SynthesisCallback;
import android.speech.tts.SynthesisRequest;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeechService;
import android.speech.tts.Voice;
import android.util.Log;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
public class TtsEngineService extends TextToSpeechService {
private static final String TAG = "TtsEngineService";
private static final int MIN_PERCENT = 50;
private static final int MAX_PERCENT = 200;
private final Object synthesisLock = new Object();
private volatile boolean stopRequested;
private VoiceRepository voices;
private Synthesizer synthesizer;
@Override
public void onCreate() {
voices = VoiceRepository.get(this);
synthesizer = new Synthesizer();
super.onCreate();
VoicePack pack = voices.getDefault();
if (pack != null) {
new Thread(() -> {
try {
synthesizer.warmUp(pack);
} catch (Throwable t) {
Log.w(TAG, "warmup failed", t);
}
}, "tts-warmup").start();
}
}
@Override
public void onDestroy() {
stopRequested = true;
synthesizer.release();
super.onDestroy();
}
@Override
protected String[] onGetLanguage() {
VoicePack pack = voices.getDefault();
if (pack == null) return new String[]{"cmn", "zho", "CN"};
Locale locale = pack.locale();
String language = locale.getLanguage();
String iso3;
try {
iso3 = locale.getISO3Language();
} catch (MissingResourceException e) {
iso3 = language;
}
return new String[]{language, iso3, locale.getCountry()};
}
@Override
protected int onIsLanguageAvailable(String lang, String country, String variant) {
return voices.hasLanguage(lang) ? TextToSpeech.LANG_AVAILABLE : TextToSpeech.LANG_NOT_SUPPORTED;
}
@Override
protected int onLoadLanguage(String lang, String country, String variant) {
return onIsLanguageAvailable(lang, country, variant);
}
@Override
public int onIsValidVoiceName(String voiceName) {
return voices.get(voiceName) != null ? TextToSpeech.SUCCESS : TextToSpeech.ERROR;
}
@Override
public int onLoadVoice(String voiceName) {
return onIsValidVoiceName(voiceName);
}
@Override
public String onGetDefaultVoiceNameFor(String lang, String country, String variant) {
VoicePack pack = voices.resolve(null, lang, country, variant);
return pack != null ? pack.name : null;
}
@Override
public List<Voice> onGetVoices() {
return voices.toVoices();
}
@Override
protected void onSynthesizeText(SynthesisRequest request, SynthesisCallback callback) {
VoicePack pack = voices.resolve(request.getVoiceName(), request.getLanguage(),
request.getCountry(), request.getVariant());
if (pack == null) {
Log.e(TAG, "no voice pack available");
callback.error();
return;
}
stopRequested = false;
synchronized (synthesisLock) {
try {
int sampleRate = synthesizer.sampleRate(pack);
int started = callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1);
if (started != 0) {
Log.e(TAG, "callback.start failed: " + started);
callback.error();
return;
}
float speed = clampPercent(request.getSpeechRate());
float pitch = clampPercent(request.getPitch());
synthesizer.synthesize(pack, request.getText(), speed, pitch,
callback, () -> stopRequested);
callback.done();
} catch (Throwable t) {
Log.e(TAG, "synthesis failed", t);
callback.error();
} finally {
stopRequested = false;
}
}
}
@Override
protected void onStop() {
stopRequested = true;
}
private static float clampPercent(int percent) {
int value = Math.max(MIN_PERCENT, Math.min(MAX_PERCENT, percent));
return value / 100f;
}
}
@@ -0,0 +1,40 @@
package com.ttstd.tts.engine;
import java.io.File;
import java.util.Locale;
final class VoicePack {
final String name;
final String localeTag;
final String label;
final int speakerId;
final int quality;
final String modelPath;
final String lexiconPath;
final String tokensPath;
final String dataDir;
final String ruleFsts;
final String modelSha256;
final File root;
VoicePack(String name, String localeTag, String label, int speakerId, int quality,
String modelPath, String lexiconPath, String tokensPath, String dataDir, String ruleFsts,
String modelSha256, File root) {
this.name = name;
this.localeTag = localeTag;
this.label = label;
this.speakerId = speakerId;
this.quality = quality;
this.modelPath = modelPath;
this.lexiconPath = lexiconPath;
this.tokensPath = tokensPath;
this.dataDir = dataDir;
this.ruleFsts = ruleFsts;
this.modelSha256 = modelSha256;
this.root = root;
}
Locale locale() {
return Locale.forLanguageTag(localeTag.replace('_', '-'));
}
}
@@ -0,0 +1,282 @@
package com.ttstd.tts.engine;
import android.content.Context;
import android.content.SharedPreferences;
import android.speech.tts.Voice;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
final class VoiceRepository {
private static final String TAG = "TtsVoiceRepository";
private static final String SYSTEM_ROOT = "/system/tts/voices";
private static final String USER_DIR = "user";
static final String PREFS = "tts_settings";
static final String KEY_DEFAULT_VOICE = "default_voice";
private static volatile VoiceRepository current;
private volatile LinkedHashMap<String, VoicePack> packs = new LinkedHashMap<>();
private volatile String defaultName = "";
private final Context context;
private final SharedPreferences prefs;
private VoiceRepository(Context context) {
this.context = context.getApplicationContext();
this.prefs = this.context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
}
static VoiceRepository get(Context context) {
VoiceRepository repo = current;
if (repo == null) {
synchronized (VoiceRepository.class) {
repo = current;
if (repo == null) {
repo = new VoiceRepository(context);
repo.reload();
current = repo;
}
}
}
return repo;
}
static File userDir(Context context) {
return new File(context.getFilesDir(), "voices/" + USER_DIR);
}
void reload() {
LinkedHashMap<String, VoicePack> merged = new LinkedHashMap<>();
String firstDefault = "";
for (File root : roots()) {
File manifest = new File(root, "manifest.json");
if (!manifest.isFile()) continue;
try (InputStream in = new FileInputStream(manifest)) {
JSONObject json = new JSONObject(readAll(in));
String rootDefault = parse(root, json, merged);
if (firstDefault.isEmpty()) firstDefault = rootDefault;
} catch (Exception e) {
Log.e(TAG, "failed to load voices from " + root, e);
}
}
if (!merged.containsKey(firstDefault)) {
firstDefault = merged.isEmpty() ? "" : merged.keySet().iterator().next();
}
packs = merged;
defaultName = firstDefault;
Log.i(TAG, "voices " + merged.keySet());
}
private List<File> roots() {
List<File> roots = new ArrayList<>();
roots.add(new File(SYSTEM_ROOT));
roots.add(new File(context.getFilesDir(), "voices"));
File external = context.getExternalFilesDir(null);
if (external != null) roots.add(new File(external, "voices"));
File[] imports = userDir(context).listFiles(File::isDirectory);
if (imports != null) {
Arrays.sort(imports);
roots.addAll(Arrays.asList(imports));
}
return roots;
}
static final int INVALID_HASH = -1;
static int validate(File root) {
File manifest = new File(root, "manifest.json");
if (!manifest.isFile()) return 0;
try (InputStream in = new FileInputStream(manifest)) {
LinkedHashMap<String, VoicePack> packs = new LinkedHashMap<>();
parse(root, new JSONObject(readAll(in)), packs);
if (packs.isEmpty()) return 0;
for (VoicePack pack : packs.values()) {
if (!usable(pack)) return 0;
if (pack.modelSha256.isEmpty()) return INVALID_HASH;
if (!pack.modelSha256.equalsIgnoreCase(sha256(new File(pack.modelPath)))) {
return INVALID_HASH;
}
}
return packs.size();
} catch (Exception e) {
Log.w(TAG, "invalid voice pack at " + root, e);
return 0;
}
}
private static String sha256(File file) {
try (InputStream in = new FileInputStream(file)) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] buf = new byte[64 * 1024];
int n;
while ((n = in.read(buf)) > 0) digest.update(buf, 0, n);
StringBuilder hex = new StringBuilder();
for (byte b : digest.digest()) hex.append(String.format(Locale.ROOT, "%02x", b));
return hex.toString();
} catch (Exception e) {
Log.w(TAG, "sha256 failed for " + file, e);
return "";
}
}
private static boolean usable(VoicePack pack) {
if (!new File(pack.modelPath).isFile()) return false;
if (!pack.tokensPath.isEmpty() && !new File(pack.tokensPath).isFile()) return false;
if (!pack.lexiconPath.isEmpty() && !new File(pack.lexiconPath).isFile()) return false;
for (String rule : pack.ruleFsts.split(",")) {
if (!rule.isEmpty() && !new File(rule).isFile()) return false;
}
return true;
}
private static String readAll(InputStream in) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
private static String parse(File root, JSONObject json, LinkedHashMap<String, VoicePack> into) throws Exception {
String rootDefault = json.optString("default", "");
JSONArray voices = json.optJSONArray("voices");
if (voices == null) return rootDefault;
for (int i = 0; i < voices.length(); i++) {
JSONObject o = voices.getJSONObject(i);
String dir = o.optString("dir", "");
File base = dir.isEmpty() ? root : new File(root, dir);
String lexicon = o.optString("lexicon", "");
String tokens = o.optString("tokens", "tokens.txt");
String dataDir = o.optString("dataDir", "");
StringBuilder rules = new StringBuilder();
JSONArray ruleFsts = o.optJSONArray("ruleFsts");
if (ruleFsts != null) {
for (int j = 0; j < ruleFsts.length(); j++) {
if (rules.length() > 0) rules.append(',');
rules.append(new File(base, ruleFsts.getString(j)).getAbsolutePath());
}
}
String name = o.getString("name");
VoicePack pack = new VoicePack(
name,
o.optString("locale", "zh-CN"),
o.optString("label", name),
o.optInt("speakerId", 0),
o.optInt("quality", Voice.QUALITY_NORMAL),
new File(base, o.getString("model")).getAbsolutePath(),
lexicon.isEmpty() ? "" : new File(base, lexicon).getAbsolutePath(),
tokens.isEmpty() ? "" : new File(base, tokens).getAbsolutePath(),
dataDir.isEmpty() ? "" : new File(base, dataDir).getAbsolutePath(),
rules.toString(),
o.optString("sha256", ""),
root);
if (!usable(pack)) {
Log.w(TAG, "skip unusable voice " + name + " at " + root);
continue;
}
into.put(pack.name, pack);
}
return rootDefault;
}
VoicePack get(String name) {
return name == null ? null : packs.get(name);
}
List<VoicePack> all() {
return new ArrayList<>(packs.values());
}
VoicePack getDefault() {
LinkedHashMap<String, VoicePack> snapshot = packs;
String saved = prefs.getString(KEY_DEFAULT_VOICE, "");
VoicePack pack = snapshot.get(saved);
return pack != null ? pack : snapshot.get(defaultName);
}
VoicePack resolve(String voiceName, String language, String country, String variant) {
VoicePack named = get(voiceName);
if (named != null) return named;
String want = normalizeLanguage(language);
if (!want.isEmpty()) {
for (VoicePack pack : packs.values()) {
Locale locale = pack.locale();
if (!locale.getLanguage().equals(want)) continue;
if (country == null || country.isEmpty() || locale.getCountry().equalsIgnoreCase(country)) {
return pack;
}
}
for (VoicePack pack : packs.values()) {
if (pack.locale().getLanguage().equals(want)) return pack;
}
}
return getDefault();
}
boolean hasLanguage(String language) {
String want = normalizeLanguage(language);
if (want.isEmpty()) return false;
for (VoicePack pack : packs.values()) {
if (pack.locale().getLanguage().equals(want)) return true;
}
return false;
}
boolean isUserPack(VoicePack pack) {
String base = userDir(context).getAbsolutePath() + File.separator;
return pack.root.getAbsolutePath().startsWith(base);
}
boolean deleteUserPack(VoicePack pack) {
if (!isUserPack(pack) || !deleteTree(pack.root)) return false;
reload();
return true;
}
private static boolean deleteTree(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) for (File child : children) deleteTree(child);
}
return file.delete();
}
List<Voice> toVoices() {
List<Voice> list = new ArrayList<>();
for (VoicePack pack : packs.values()) {
list.add(new Voice(pack.name, pack.locale(), pack.quality,
Voice.LATENCY_NORMAL, false, Collections.emptySet()));
}
return list;
}
static String normalizeLanguage(String language) {
if (language == null) return "";
String lang = language.toLowerCase(Locale.ROOT);
switch (lang) {
case "cmn":
case "zho":
case "zh":
return "zh";
default:
return lang;
}
}
}
@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/settings_voice"
android:textSize="18sp"
android:textStyle="bold" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="12dp">
<RadioGroup
android:id="@+id/voice_group"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<Button
android:id="@+id/btn_import"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/settings_import" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:enabled="false"
android:text="@string/settings_delete" />
<Button
android:id="@+id/btn_preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="@string/settings_preview" />
</LinearLayout>
<TextView
android:id="@+id/import_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:textSize="14sp" />
<TextView
android:id="@+id/voice_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:textSize="14sp" />
</LinearLayout>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TTStd 语音引擎</string>
<string name="settings_title">语音引擎设置</string>
<string name="settings_voice">默认音色</string>
<string name="settings_preview">试听</string>
<string name="settings_sample">你好,我是朝阳的声音。</string>
<string name="settings_empty">未找到语音包</string>
<string name="settings_import">导入语音包</string>
<string name="settings_delete">删除导入包</string>
<string name="settings_importing">正在导入,请稍候…</string>
<string name="settings_import_ok">已导入 %1$d 个语音包</string>
<string name="settings_import_fail">导入失败:所选文件夹不是有效的语音包</string>
<string name="settings_import_hash">导入失败:模型 SHA-256 校验未通过</string>
<string name="settings_delete_builtin">内置语音包不能删除</string>
<string name="settings_delete_confirm">删除语音包“%1$s”及其全部文件?</string>
<string name="settings_deleted">已删除</string>
</resources>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="EngineTheme" parent="@android:style/Theme.DeviceDefault">
<item name="android:windowOptOutEdgeToEdgeEnforcement">true</item>
</style>
</resources>
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<tts-engine xmlns:android="http://schemas.android.com/apk/res/android"
android:settingsActivity="com.ttstd.tts.engine.SettingsActivity" />