Skip to content

Commit

Permalink
TextToSpeechAPI: Synthesize speech output to WAV file
Browse files Browse the repository at this point in the history
Only first line is synthesized (API limitation).
Fixes: termux#356
  • Loading branch information
Menyadar committed Sep 25, 2022
1 parent 11eff56 commit fafdd5c
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion app/src/main/java/com/termux/api/apis/TextToSpeechAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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() {
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
}
}
}
}
Expand Down

0 comments on commit fafdd5c

Please sign in to comment.