eSpeak NG is an open source speech synthesizer that supports more than hundred languages and accents.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TtsService.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (C) 2022 Beka Gozalishvili
  3. * Copyright (C) 2012-2015 Reece H. Dunn
  4. * Copyright (C) 2011 Google Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. /*
  19. * This file implements the Android Text-to-Speech engine for eSpeak.
  20. *
  21. * Android Version: 4.0 (Ice Cream Sandwich)
  22. * API Version: 14
  23. */
  24. package com.reecedunn.espeak;
  25. import android.annotation.SuppressLint;
  26. import android.content.BroadcastReceiver;
  27. import android.content.Context;
  28. import android.content.Intent;
  29. import android.content.IntentFilter;
  30. import android.media.AudioTrack;
  31. import android.os.Build;
  32. import android.os.Bundle;
  33. import android.preference.PreferenceManager;
  34. import android.speech.tts.SynthesisCallback;
  35. import android.speech.tts.SynthesisRequest;
  36. import android.speech.tts.TextToSpeech;
  37. import android.speech.tts.TextToSpeechService;
  38. import android.util.Log;
  39. import android.util.Pair;
  40. import com.reecedunn.espeak.SpeechSynthesis.SynthReadyCallback;
  41. import java.util.ArrayList;
  42. import java.util.HashMap;
  43. import java.util.HashSet;
  44. import java.util.List;
  45. import java.util.Locale;
  46. import java.util.Map;
  47. import java.util.Set;
  48. /**
  49. * Implements the eSpeak engine as a {@link TextToSpeechService}.
  50. *
  51. * @author [email protected] (Reece H. Dunn)
  52. * @author [email protected] (Alan Viverette)
  53. */
  54. @SuppressLint("NewApi")
  55. public class TtsService extends TextToSpeechService {
  56. public static final String ESPEAK_INITIALIZED = "com.reecedunn.espeak.ESPEAK_INITIALIZED";
  57. private static final String TAG = TtsService.class.getSimpleName();
  58. private static Context storageContext;
  59. private static final boolean DEBUG = false;
  60. private SpeechSynthesis mEngine;
  61. private SynthesisCallback mCallback;
  62. private final Map<String, Voice> mAvailableVoices = new HashMap<String, Voice>();
  63. protected Voice mMatchingVoice = null;
  64. private BroadcastReceiver mOnLanguagesDownloaded = null;
  65. @Override
  66. public void onCreate() {
  67. storageContext = EspeakApp.getStorageContext();
  68. storageContext.moveSharedPreferencesFrom(this, this.getPackageName() + "_preferences");
  69. initializeTtsEngine();
  70. super.onCreate();
  71. }
  72. @Override
  73. public void onDestroy() {
  74. super.onDestroy();
  75. if (mOnLanguagesDownloaded != null) {
  76. unregisterReceiver(mOnLanguagesDownloaded);
  77. }
  78. }
  79. /**
  80. * Sets up the native eSpeak engine.
  81. */
  82. private void initializeTtsEngine() {
  83. if (mEngine != null) {
  84. mEngine.stop();
  85. mEngine = null;
  86. }
  87. mEngine = new SpeechSynthesis(storageContext, mSynthCallback);
  88. mAvailableVoices.clear();
  89. for (Voice voice : mEngine.getAvailableVoices()) {
  90. mAvailableVoices.put(voice.name, voice);
  91. }
  92. final Intent intent = new Intent(ESPEAK_INITIALIZED);
  93. sendBroadcast(intent);
  94. }
  95. @Override
  96. protected String[] onGetLanguage() {
  97. // This is used to specify the language requested from GetSampleText.
  98. if (mMatchingVoice == null) {
  99. return new String[] { "eng", "GBR", "" };
  100. }
  101. return new String[] {
  102. mMatchingVoice.locale.getISO3Language(),
  103. mMatchingVoice.locale.getISO3Country(),
  104. mMatchingVoice.locale.getVariant()
  105. };
  106. }
  107. private Pair<Voice, Integer> findVoice(String language, String country, String variant) {
  108. if (!CheckVoiceData.hasBaseResources(storageContext) || CheckVoiceData.canUpgradeResources(storageContext)) {
  109. if (mOnLanguagesDownloaded == null) {
  110. mOnLanguagesDownloaded = new BroadcastReceiver() {
  111. @Override
  112. public void onReceive(Context context, Intent intent) {
  113. initializeTtsEngine();
  114. }
  115. };
  116. final IntentFilter filter = new IntentFilter(DownloadVoiceData.BROADCAST_LANGUAGES_UPDATED);
  117. registerReceiver(mOnLanguagesDownloaded, filter);
  118. }
  119. final Intent intent = new Intent(storageContext, DownloadVoiceData.class);
  120. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  121. startActivity(intent);
  122. return new Pair<>(null, TextToSpeech.LANG_MISSING_DATA);
  123. }
  124. final Locale query = new Locale(language, country, variant);
  125. Voice languageVoice = null;
  126. Voice countryVoice = null;
  127. synchronized (mAvailableVoices) {
  128. for (Voice voice : mAvailableVoices.values()) {
  129. switch (voice.match(query)) {
  130. case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
  131. return new Pair<>(voice, TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE);
  132. case TextToSpeech.LANG_COUNTRY_AVAILABLE:
  133. countryVoice = voice;
  134. case TextToSpeech.LANG_AVAILABLE:
  135. languageVoice = voice;
  136. break;
  137. }
  138. }
  139. }
  140. if (languageVoice == null) {
  141. return new Pair<>(null, TextToSpeech.LANG_NOT_SUPPORTED);
  142. } else if (countryVoice == null) {
  143. return new Pair<>(languageVoice, TextToSpeech.LANG_AVAILABLE);
  144. } else {
  145. return new Pair<>(countryVoice, TextToSpeech.LANG_COUNTRY_AVAILABLE);
  146. }
  147. }
  148. private Pair<Voice, Integer> getDefaultVoiceFor(String language, String country, String variant) {
  149. final Pair<Voice, Integer> match = findVoice(language, country, variant);
  150. switch (match.second) {
  151. case TextToSpeech.LANG_AVAILABLE:
  152. if (language.equals("fr") || language.equals("fra")) {
  153. return new Pair<>(findVoice(language, "FRA", "").first, match.second);
  154. }
  155. if (language.equals("pt") || language.equals("por")) {
  156. return new Pair<>(findVoice(language, "PRT", "").first, match.second);
  157. }
  158. return new Pair<>(findVoice(language, "", "").first, match.second);
  159. case TextToSpeech.LANG_COUNTRY_AVAILABLE:
  160. if ((language.equals("vi") || language.equals("vie")) && (country.equals("VN") || country.equals("VNM"))) {
  161. return new Pair<>(findVoice(language, country, "hue").first, match.second);
  162. }
  163. return new Pair<>(findVoice(language, country, "").first, match.second);
  164. default:
  165. return match;
  166. }
  167. }
  168. @Override
  169. protected int onIsLanguageAvailable(String language, String country, String variant) {
  170. return findVoice(language, country, variant).second;
  171. }
  172. @Override
  173. protected int onLoadLanguage(String language, String country, String variant) {
  174. final Pair<Voice, Integer> match = getDefaultVoiceFor(language, country, variant);
  175. if (match.first != null) {
  176. mMatchingVoice = match.first;
  177. }
  178. return match.second;
  179. }
  180. @Override
  181. protected Set<String> onGetFeaturesForLanguage(String lang, String country, String variant) {
  182. return new HashSet<String>();
  183. }
  184. @Override
  185. public String onGetDefaultVoiceNameFor(String language, String country, String variant) {
  186. final Voice match = getDefaultVoiceFor(language, country, variant).first;
  187. return (match == null) ? null : match.name;
  188. }
  189. @Override
  190. public List<android.speech.tts.Voice> onGetVoices() {
  191. List<android.speech.tts.Voice> voices = new ArrayList<android.speech.tts.Voice>();
  192. for (Voice voice : mAvailableVoices.values()) {
  193. int quality = android.speech.tts.Voice.QUALITY_NORMAL;
  194. int latency = android.speech.tts.Voice.LATENCY_VERY_LOW;
  195. Locale locale = new Locale(voice.locale.getISO3Language(), voice.locale.getISO3Country(), voice.locale.getVariant());
  196. Set<String> features = onGetFeaturesForLanguage(locale.getLanguage(), locale.getCountry(), locale.getVariant());
  197. voices.add(new android.speech.tts.Voice(voice.name, voice.locale, quality, latency, false, features));
  198. }
  199. return voices;
  200. }
  201. @Override
  202. public int onIsValidVoiceName(String name) {
  203. Voice voice = mAvailableVoices.get(name);
  204. return (voice == null) ? TextToSpeech.ERROR : TextToSpeech.SUCCESS;
  205. }
  206. @Override
  207. public int onLoadVoice(String name) {
  208. Voice voice = mAvailableVoices.get(name);
  209. if (voice == null) {
  210. return TextToSpeech.ERROR;
  211. }
  212. mMatchingVoice = voice;
  213. return TextToSpeech.SUCCESS;
  214. }
  215. @Override
  216. protected void onStop() {
  217. Log.i(TAG, "Received stop request.");
  218. mEngine.stop();
  219. }
  220. @SuppressWarnings("deprecation")
  221. private String getRequestString(SynthesisRequest request) {
  222. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  223. return request.getCharSequenceText().toString();
  224. } else {
  225. return request.getText();
  226. }
  227. }
  228. private int selectVoice(SynthesisRequest request) {
  229. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  230. final String name = request.getVoiceName();
  231. if (name != null && !name.isEmpty()) {
  232. return onLoadVoice(name);
  233. }
  234. }
  235. final int result = onLoadLanguage(request.getLanguage(), request.getCountry(), request.getVariant());
  236. switch (result) {
  237. case TextToSpeech.LANG_MISSING_DATA:
  238. case TextToSpeech.LANG_NOT_SUPPORTED:
  239. return TextToSpeech.ERROR;
  240. }
  241. return TextToSpeech.SUCCESS;
  242. }
  243. @Override
  244. protected synchronized void onSynthesizeText(SynthesisRequest request, SynthesisCallback callback) {
  245. if (mMatchingVoice == null)
  246. return;
  247. String text = getRequestString(request);
  248. if (text == null)
  249. return;
  250. if (DEBUG) {
  251. Log.i(TAG, "Received synthesis request: {language=\"" + mMatchingVoice.name + "\"}");
  252. final Bundle params = request.getParams();
  253. for (String key : params.keySet()) {
  254. Log.v(TAG,
  255. "Synthesis request contained param {" + key + ", " + params.get(key) + "}");
  256. }
  257. }
  258. if (text.startsWith("<?xml"))
  259. {
  260. // eSpeak does not recognise/skip "<?...?>" preprocessing tags,
  261. // so need to remove these before passing to synthesize.
  262. text = text.substring(text.indexOf("?>") + 2).trim();
  263. }
  264. mCallback = callback;
  265. mCallback.start(mEngine.getSampleRate(), mEngine.getAudioFormat(), mEngine.getChannelCount());
  266. final VoiceSettings settings = new VoiceSettings(PreferenceManager.getDefaultSharedPreferences(storageContext), mEngine);
  267. mEngine.setVoice(mMatchingVoice, settings.getVoiceVariant());
  268. mEngine.Rate.setValue(settings.getRate(), request.getSpeechRate());
  269. mEngine.Pitch.setValue(settings.getPitch(), request.getPitch());
  270. mEngine.PitchRange.setValue(settings.getPitchRange());
  271. mEngine.Volume.setValue(settings.getVolume());
  272. mEngine.Punctuation.setValue(settings.getPunctuationLevel());
  273. mEngine.setPunctuationCharacters(settings.getPunctuationCharacters());
  274. mEngine.synthesize(text, text.startsWith("<speak"));
  275. }
  276. /**
  277. * Pipes synthesizer output from native eSpeak to an {@link AudioTrack}.
  278. */
  279. private final SpeechSynthesis.SynthReadyCallback mSynthCallback = new SynthReadyCallback() {
  280. @Override
  281. public void onSynthDataReady(byte[] audioData) {
  282. if ((audioData == null) || (audioData.length == 0)) {
  283. onSynthDataComplete();
  284. return;
  285. }
  286. final int maxBytesToCopy = mCallback.getMaxBufferSize();
  287. int offset = 0;
  288. while (offset < audioData.length) {
  289. final int bytesToWrite = Math.min(maxBytesToCopy, (audioData.length - offset));
  290. mCallback.audioAvailable(audioData, offset, bytesToWrite);
  291. offset += bytesToWrite;
  292. }
  293. }
  294. @Override
  295. public void onSynthDataComplete() {
  296. mCallback.done();
  297. }
  298. };
  299. }