From fafdd5c8bc4c18b4483ec990252b8e48c5b92bc7 Mon Sep 17 00:00:00 2001 From: Menyadar <> Date: Sun, 25 Sep 2022 19:58:32 +0200 Subject: [PATCH] TextToSpeechAPI: Synthesize speech output to WAV file Only first line is synthesized (API limitation). Fixes: #356 --- .../com/termux/api/apis/TextToSpeechAPI.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/termux/api/apis/TextToSpeechAPI.java b/app/src/main/java/com/termux/api/apis/TextToSpeechAPI.java index 2dae2dd1..efb26f3e 100644 --- a/app/src/main/java/com/termux/api/apis/TextToSpeechAPI.java +++ b/app/src/main/java/com/termux/api/apis/TextToSpeechAPI.java @@ -16,6 +16,7 @@ import com.termux.shared.logger.Logger; import java.io.BufferedReader; +import java.io.File; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; @@ -37,6 +38,9 @@ public static class TextToSpeechService extends IntentService { TextToSpeech mTts; final CountDownLatch mTtsLatch = new CountDownLatch(1); + // file we're recording to + protected static File file; + private static final String LOG_TAG = "TextToSpeechService"; public TextToSpeechService() { @@ -67,6 +71,7 @@ protected void onHandleIntent(final Intent intent) { final String speechRegion = intent.getStringExtra("region"); final String speechVariant = intent.getStringExtra("variant"); final String speechEngine = intent.getStringExtra("engine"); + final String speechFile = intent.getStringExtra("file"); final float speechPitch = intent.getFloatExtra("pitch", 1.0f); // STREAM_MUSIC is the default audio stream for TTS, see: @@ -97,6 +102,14 @@ protected void onHandleIntent(final Intent intent) { } final int streamToUse = streamToUseInt; + if (speechFile != null) { + file = new File(speechFile); + if (!file.canWrite()) { + Logger.logError(LOG_TAG, "Can't write to file: " + file.getName()); + return; + } + } + mTts = new TextToSpeech(this, status -> { if (status == TextToSpeech.SUCCESS) { mTtsLatch.countDown(); @@ -187,7 +200,12 @@ public void onDone(String utteranceId) { while ((line = reader.readLine()) != null) { if (!line.isEmpty()) { submittedUtterances++; - mTts.speak(line, TextToSpeech.QUEUE_ADD, params, utteranceId); + if (speechFile != null) { + mTts.synthesizeToFile(line, params, file, utteranceId); + break; + } else { + mTts.speak(line, TextToSpeech.QUEUE_ADD, params, utteranceId); + } } } }