feat: 增加在线语音 SDK 和音色管理后台,完善引擎适配

This commit is contained in:
tongtong committed 2026-11-23 19:02:44 +08:00
1 parent 1856de97bc
commit a532ba4e0f
71 files changed
+3189 -472

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
plugins { id 'com.android.library' }
android {
namespace 'com.ttstd.tts.sdk'
compileSdk 37
defaultConfig { minSdk 23; consumerProguardFiles 'consumer-rules.pro' }
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8; targetCompatibility JavaVersion.VERSION_1_8 }
publishing { singleVariant('release') }
lint { abortOnError true }
}
dependencies { testImplementation 'junit:junit:4.13.2' }
apply from: rootProject.file('gradle/gitea-publish.gradle')
+1
View File
@@ -0,0 +1 @@
# No reflection or native dependencies.
@@ -0,0 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"><uses-permission android:name="android.permission.INTERNET" /></manifest>
@@ -0,0 +1,200 @@
package com.ttstd.tts.sdk;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Standalone HTTP TTS client. No TTS engine installation or model is required.
* Each new request replaces the previous request. Listener callbacks run on the main thread.
* Call close() when the owner is destroyed. Tokens are obtained per request and never logged.
*/
public final class OnlineTtsClient implements AutoCloseable {
public static final String DEFAULT_ENDPOINT="https://tts.ttstd.com/tts";
public interface TokenProvider { String getToken(); }
public interface Listener {
default void onStart() {}
default void onCompleted() {}
default void onError(int httpStatus, String message) {}
default void onCancelled() {}
}
private final Context context;
private final URL endpoint;
private final TokenProvider tokens;
private final Handler main=new Handler(Looper.getMainLooper());
private final ThreadPoolExecutor worker=new ThreadPoolExecutor(1,1,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(1));
private Job current;
private boolean closed;
public OnlineTtsClient(Context context,String endpoint,TokenProvider tokens) {
this.context=context.getApplicationContext();
try {
this.endpoint=new URL(endpoint);
if (!this.endpoint.getProtocol().equals("https") || this.endpoint.getHost().isEmpty()
|| this.endpoint.getUserInfo()!=null || this.endpoint.getQuery()!=null
|| this.endpoint.getRef()!=null) throw new IllegalArgumentException("HTTPS endpoint without credentials/query required");
} catch(MalformedURLException e) { throw new IllegalArgumentException("Invalid HTTPS endpoint"); }
if(tokens==null) throw new IllegalArgumentException("TokenProvider required");
this.tokens=tokens;
}
public synchronized void speak(SpeechRequest request,Listener listener) { submit(request,null,listener); }
/** Synthesize to a caller-owned WAV file without playback. Existing output is replaced only on success. */
public synchronized void synthesizeToFile(SpeechRequest request,File destination,Listener listener) {
if(destination==null) throw new IllegalArgumentException("Destination required");
submit(request,destination,listener);
}
private void submit(SpeechRequest request,File destination,Listener listener) {
if(closed) throw new IllegalStateException("Client closed");
if(request==null || listener==null) throw new IllegalArgumentException("Request and listener required");
stop();
Job job=new Job(request,destination,listener);
current=job;
worker.execute(() -> execute(job));
}
public synchronized void stop() {
worker.getQueue().clear();
if(current!=null) {
current.cancelled=true;
HttpURLConnection connection=current.connection;
if(connection!=null) connection.disconnect();
finish(current,2,0,"Cancelled");
current=null;
}
}
@Override public synchronized void close() {
if(closed) return;
closed=true;
stop();
worker.shutdownNow();
}
private void execute(Job job) {
File audio=null;
int status=0;
try {
if(job.cancelled) return;
String token=tokens.getToken();
if(token==null || token.trim().isEmpty() || token.indexOf('\r')>=0 || token.indexOf('\n')>=0)
throw new IOException("Access token is missing or invalid");
byte[] body=new JSONObject().put("text",job.request.text).put("voice","zh-CN")
.put("speed",job.request.speed).put("pitch",job.request.pitch)
.toString().getBytes(StandardCharsets.UTF_8);
HttpURLConnection connection=(HttpURLConnection)endpoint.openConnection();
job.connection=connection;
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(8000);
connection.setReadTimeout(30000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(body.length);
connection.setRequestProperty("Content-Type","application/json; charset=utf-8");
connection.setRequestProperty("Authorization","Bearer "+token.trim());
if(job.cancelled) return;
try(OutputStream out=connection.getOutputStream()) { out.write(body); }
status=connection.getResponseCode();
if(status!=200) throw new IOException("TTS HTTP "+status);
File parent=job.destination==null ? context.getCacheDir() : job.destination.getAbsoluteFile().getParentFile();
audio=File.createTempFile("tts-sdk-",".wav",parent);
job.temporary=audio;
try(InputStream in=connection.getInputStream(); OutputStream out=new FileOutputStream(audio)) {
byte[] buffer=new byte[8192]; long total=0; int n;
while((n=in.read(buffer))!=-1) {
if(job.cancelled) return;
total+=n;
if(total>21L*1024*1024) throw new IOException("Audio response too large");
out.write(buffer,0,n);
}
}
connection.disconnect();
job.connection=null;
try(InputStream in=new FileInputStream(audio)) {
WavPcmReader wav=new WavPcmReader(in);
byte[] check=new byte[8192];
while(wav.readPcm(check)!=-1) if(job.cancelled) return;
}
if(job.cancelled) return;
if(job.destination!=null) {
synchronized(this) {
if(job.cancelled) return;
if(!audio.renameTo(job.destination)) throw new IOException("Unable to publish WAV file");
}
finish(job,0,0,"");
} else {
File ready=audio;
main.post(() -> play(job,ready));
audio=null; // Main-thread player owns cleanup from here.
}
} catch(Exception e) {
if(!job.cancelled) finish(job,1,status,
status!=0 && status!=200 ? "TTS HTTP "+status : e instanceof SocketTimeoutException ? "Network timeout" : "Online synthesis failed");
} finally {
HttpURLConnection connection=job.connection;
if(connection!=null) connection.disconnect();
job.connection=null;
if(audio!=null) audio.delete();
}
}
private void play(Job job,File audio) {
if(job.cancelled) { audio.delete(); return; }
try {
AudioManager manager=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
job.audioManager=manager;
job.focus=change -> {
if(change==AudioManager.AUDIOFOCUS_LOSS || change==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
synchronized(this) { if(current==job) stop(); }
}
};
if(manager==null || manager.requestAudioFocus(job.focus,AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)!=AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
throw new IOException("Audio focus unavailable");
MediaPlayer player=new MediaPlayer();
job.player=player;
player.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build());
player.setDataSource(audio.getAbsolutePath());
player.setOnPreparedListener(p -> {
if(job.cancelled) return;
p.start();
job.listener.onStart();
});
player.setOnCompletionListener(p -> finish(job,0,0,""));
player.setOnErrorListener((p,what,extra) -> { finish(job,1,0,"Audio playback failed"); return true; });
player.prepareAsync();
} catch(Exception e) { finish(job,1,0,"Audio playback failed"); }
}
private void finish(Job job,int outcome,int status,String message) {
if(!job.terminal.compareAndSet(false,true)) return;
main.post(() -> {
if(job.player!=null) { job.player.release(); job.player=null; }
if(job.audioManager!=null && job.focus!=null) job.audioManager.abandonAudioFocus(job.focus);
if(job.temporary!=null) job.temporary.delete();
synchronized(this) { if(current==job) current=null; }
if(outcome==0) job.listener.onCompleted();
else if(outcome==2) job.listener.onCancelled();
else job.listener.onError(status,message);
});
}
private static final class Job {
final SpeechRequest request;
final File destination;
final Listener listener;
final AtomicBoolean terminal=new AtomicBoolean();
volatile boolean cancelled;
volatile HttpURLConnection connection;
volatile File temporary;
AudioManager audioManager;
AudioManager.OnAudioFocusChangeListener focus;
MediaPlayer player; // Accessed only on main thread.
Job(SpeechRequest request,File destination,Listener listener) {
this.request=request; this.destination=destination; this.listener=listener;
}
}
}
@@ -0,0 +1,17 @@
package com.ttstd.tts.sdk;
/** Immutable validated online synthesis parameters. */
public final class SpeechRequest {
public final String text;
public final float speed;
public final float pitch;
public SpeechRequest(String text, float speed, float pitch) {
if (text == null || text.trim().isEmpty() || text.codePointCount(0,text.length()) > 300)
throw new IllegalArgumentException("Text must contain 1..300 characters");
if (Float.isNaN(speed) || Float.isInfinite(speed) || Float.isNaN(pitch) || Float.isInfinite(pitch))
throw new IllegalArgumentException("Speed and pitch must be finite");
this.text=text.trim();
this.speed=Math.max(0.5f,Math.min(2f,speed));
this.pitch=Math.max(0.5f,Math.min(2f,pitch));
}
}
@@ -0,0 +1,86 @@
package com.ttstd.tts.sdk;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/** Bounded RIFF parser: do not assume WAV has a fixed 44-byte header. */
final class WavPcmReader {
private static final long MAX_AUDIO = 20L * 1024 * 1024;
final InputStream input;
final int sampleRate;
long remaining;
WavPcmReader(InputStream input) throws IOException {
this.input = input;
byte[] riff = read(input, 12);
if (!tag(riff,0).equals("RIFF") || !tag(riff,8).equals("WAVE"))
throw new IOException("Not a RIFF WAV");
long riffRemaining = uint(riff,4)-4;
int rate = 0;
long metadata = 0;
while (riffRemaining >= 8) {
byte[] header = read(input,8);
long size = uint(header,4);
riffRemaining -= 8;
if (size > riffRemaining) throw new IOException("Invalid RIFF chunk length");
String id = tag(header,0);
if (id.equals("data")) {
if (rate == 0 || size == 0 || size > MAX_AUDIO || (size & 1) != 0)
throw new IOException("Invalid PCM data");
sampleRate = rate;
remaining = size;
return;
}
metadata += size;
if (metadata > 1024 * 1024) throw new IOException("WAV metadata too large");
if (id.equals("fmt ")) {
if (size < 16) throw new IOException("Invalid WAV format");
byte[] fmt = read(input,16);
rate = (int)uint(fmt,4);
if (ushort(fmt,0)!=1 || ushort(fmt,2)!=1 || ushort(fmt,14)!=16
|| ushort(fmt,12)!=2 || rate<8000 || rate>48000
|| uint(fmt,8)!=rate*2L) throw new IOException("Expected mono PCM16 WAV");
skip(input,size-16);
} else skip(input,size);
skip(input,size & 1);
riffRemaining -= size + (size & 1);
}
throw new IOException("WAV has no audio data");
}
int readPcm(byte[] buffer) throws IOException {
if (remaining == 0) return -1;
int count = (int)Math.min(buffer.length,remaining);
int at = 0;
while (at < count) {
int n=input.read(buffer,at,count-at);
if (n<0) throw new EOFException("Truncated WAV audio");
if (n==0) continue;
at+=n;
}
remaining-=count;
return count;
}
private static byte[] read(InputStream in,int size) throws IOException {
byte[] data=new byte[size];
int at=0;
while(at<size) {
int n=in.read(data,at,size-at);
if(n<0) throw new EOFException("Truncated WAV header");
at+=n;
}
return data;
}
private static void skip(InputStream in,long count) throws IOException {
byte[] scratch=new byte[4096];
while(count>0) {
int n=in.read(scratch,0,(int)Math.min(count,scratch.length));
if(n<0) throw new EOFException("Truncated WAV chunk");
count-=n;
}
}
private static int ushort(byte[] b,int i) { return (b[i]&255)|((b[i+1]&255)<<8); }
private static long uint(byte[] b,int i) { return (ushort(b,i)&65535L)|((long)ushort(b,i+2)<<16); }
private static String tag(byte[] b,int i) { return new String(b,i,4,StandardCharsets.US_ASCII); }
}
@@ -0,0 +1,10 @@
package com.ttstd.tts.sdk;
import org.junit.Test;
import static org.junit.Assert.*;
public class SpeechRequestTest {
@Test public void clampsParameters() { SpeechRequest r=new SpeechRequest(" hello ",0.1f,5f); assertEquals("hello",r.text); assertEquals(0.5f,r.speed,0); assertEquals(2,r.pitch,0); }
@Test(expected=IllegalArgumentException.class) public void rejectsEmpty() { new SpeechRequest(" ",1,1); }
@Test(expected=IllegalArgumentException.class) public void rejectsLongText() { new SpeechRequest(new String(new char[301]).replace('\0','a'),1,1); }
@Test(expected=IllegalArgumentException.class) public void rejectsNaN() { new SpeechRequest("hello",Float.NaN,1); }
@Test public void countsUnicodeCodePoints() { new SpeechRequest(new String(Character.toChars(0x1f600)),1,1); }
}
@@ -0,0 +1,46 @@
package com.ttstd.tts.sdk;
import org.junit.Test;
import java.io.*;
import java.nio.*;
import static org.junit.Assert.*;
public class WavPcmReaderTest {
private byte[] wav(boolean extra) throws Exception {
ByteArrayOutputStream out=new ByteArrayOutputStream();
DataOutputStream d=new DataOutputStream(out);
d.writeBytes("RIFF"); le(d,40+(extra?10:0)); d.writeBytes("WAVE");
if(extra) { d.writeBytes("JUNK"); le(d,1); d.write(7); d.write(0); }
d.writeBytes("fmt "); le(d,16);
d.write(new byte[]{1,0,1,0}); le(d,22050); le(d,44100);
d.write(new byte[]{2,0,16,0}); d.writeBytes("data"); le(d,4);
d.write(new byte[]{1,2,3,4}); return out.toByteArray();
}
private void le(DataOutputStream d,int value) throws Exception { d.writeInt(Integer.reverseBytes(value)); }
@Test public void parsesExtraChunksAndStreamsPcm() throws Exception {
WavPcmReader reader=new WavPcmReader(new ByteArrayInputStream(wav(true)));
assertEquals(22050,reader.sampleRate);
byte[] pcm=new byte[2];
assertEquals(2,reader.readPcm(pcm)); assertArrayEquals(new byte[]{1,2},pcm);
assertEquals(2,reader.readPcm(pcm)); assertArrayEquals(new byte[]{3,4},pcm);
assertEquals(-1,reader.readPcm(pcm));
}
@Test(expected=IOException.class) public void rejectsTruncation() throws Exception {
byte[] data=wav(false);
WavPcmReader reader=new WavPcmReader(new ByteArrayInputStream(java.util.Arrays.copyOf(data,data.length-1)));
reader.readPcm(new byte[100]);
}
@Test(expected=IOException.class) public void rejectsWrongFormat() throws Exception {
byte[] data=wav(false); data[34]=8;
new WavPcmReader(new ByteArrayInputStream(data));
}
@Test(expected=IOException.class) public void rejectsOversizedResponseBeforeAllocation() throws Exception {
byte[] data=wav(false);
ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).putInt(4,30*1024*1024+36).putInt(40,30*1024*1024);
new WavPcmReader(new ByteArrayInputStream(data));
}
@Test(expected=IOException.class) public void rejectsStereo() throws Exception {
byte[] data=wav(false); data[22]=2;
new WavPcmReader(new ByteArrayInputStream(data));
}
}