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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * Copyright (C) 2012-2013 Reece H. Dunn
  3. * Copyright (C) 2011 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*
  18. * This file implements the Android Text-to-Speech engine for eSpeak.
  19. *
  20. * Android Version: 4.0 (Ice Cream Sandwich)
  21. * API Version: 14
  22. */
  23. package com.reecedunn.espeak;
  24. import android.annotation.SuppressLint;
  25. import android.content.BroadcastReceiver;
  26. import android.content.Context;
  27. import android.content.Intent;
  28. import android.content.IntentFilter;
  29. import android.content.SharedPreferences;
  30. import android.media.AudioTrack;
  31. import android.os.Bundle;
  32. import android.preference.PreferenceManager;
  33. import android.speech.tts.SynthesisCallback;
  34. import android.speech.tts.SynthesisRequest;
  35. import android.speech.tts.TextToSpeech;
  36. import android.speech.tts.TextToSpeechService;
  37. import android.util.Log;
  38. import com.reecedunn.espeak.SpeechSynthesis.SynthReadyCallback;
  39. import com.reecedunn.espeak.SpeechSynthesis.Voice;
  40. import java.util.List;
  41. import java.util.Locale;
  42. /**
  43. * Implements the eSpeak engine as a {@link TextToSpeechService}.
  44. *
  45. * @author [email protected] (Reece H. Dunn)
  46. * @author [email protected] (Alan Viverette)
  47. */
  48. @SuppressLint("NewApi")
  49. public class TtsService extends TextToSpeechService {
  50. private static final String TAG = TtsService.class.getSimpleName();
  51. private static final boolean DEBUG = false;
  52. private static final String DEFAULT_LANGUAGE = "en";
  53. private static final String DEFAULT_COUNTRY = "uk";
  54. private static final String DEFAULT_VARIANT = "";
  55. private SpeechSynthesis mEngine;
  56. private SynthesisCallback mCallback;
  57. private List<Voice> mAvailableVoices;
  58. private Voice mMatchingVoice = null;
  59. private String mLanguage = DEFAULT_LANGUAGE;
  60. private String mCountry = DEFAULT_COUNTRY;
  61. private String mVariant = DEFAULT_VARIANT;
  62. @Override
  63. public void onCreate() {
  64. initializeTtsEngine();
  65. super.onCreate();
  66. }
  67. @Override
  68. public void onDestroy() {
  69. super.onDestroy();
  70. if (mBroadcastReceiver != null) {
  71. unregisterReceiver(mBroadcastReceiver);
  72. }
  73. }
  74. /**
  75. * Sets up the native eSpeak engine.
  76. */
  77. private void initializeTtsEngine() {
  78. if (mEngine != null) {
  79. mEngine.stop();
  80. mEngine = null;
  81. }
  82. mEngine = new SpeechSynthesis(this, mSynthCallback);
  83. mAvailableVoices = mEngine.getAvailableVoices();
  84. }
  85. @Override
  86. protected String[] onGetLanguage() {
  87. // This is used to specify the language requested from GetSampleText.
  88. return new String[] {
  89. mLanguage, mCountry, mVariant
  90. };
  91. }
  92. @Override
  93. protected int onIsLanguageAvailable(String language, String country, String variant) {
  94. if (!CheckVoiceData.hasBaseResources(this) || CheckVoiceData.canUpgradeResources(this)) {
  95. if (mBroadcastReceiver == null) {
  96. mBroadcastReceiver = new BroadcastReceiver() {
  97. @Override
  98. public void onReceive(Context context, Intent intent) {
  99. initializeTtsEngine();
  100. }
  101. };
  102. final IntentFilter filter = new IntentFilter(DownloadVoiceData.BROADCAST_LANGUAGES_UPDATED);
  103. registerReceiver(mBroadcastReceiver, filter);
  104. }
  105. final Intent intent = new Intent(this, DownloadVoiceData.class);
  106. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  107. startActivity(intent);
  108. return TextToSpeech.LANG_MISSING_DATA;
  109. }
  110. final Locale query = new Locale(language, country, variant);
  111. Voice languageVoice = null;
  112. Voice countryVoice = null;
  113. synchronized (mAvailableVoices) {
  114. for (Voice voice : mAvailableVoices) {
  115. switch (voice.match(query)) {
  116. case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
  117. mMatchingVoice = voice;
  118. return TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE;
  119. case TextToSpeech.LANG_COUNTRY_AVAILABLE:
  120. countryVoice = voice;
  121. case TextToSpeech.LANG_AVAILABLE:
  122. languageVoice = voice;
  123. break;
  124. }
  125. }
  126. }
  127. if (languageVoice == null) {
  128. mMatchingVoice = null;
  129. return TextToSpeech.LANG_NOT_SUPPORTED;
  130. } else if (countryVoice == null) {
  131. mMatchingVoice = languageVoice;
  132. return TextToSpeech.LANG_AVAILABLE;
  133. } else {
  134. mMatchingVoice = countryVoice;
  135. return TextToSpeech.LANG_COUNTRY_AVAILABLE;
  136. }
  137. }
  138. @Override
  139. protected int onLoadLanguage(String language, String country, String variant) {
  140. final int result = onIsLanguageAvailable(language, country, variant);
  141. switch (result) {
  142. case TextToSpeech.LANG_AVAILABLE:
  143. synchronized (this) {
  144. mLanguage = language;
  145. mCountry = "";
  146. mVariant = "";
  147. }
  148. break;
  149. case TextToSpeech.LANG_COUNTRY_AVAILABLE:
  150. synchronized (this) {
  151. mLanguage = language;
  152. mCountry = ((country == null) ? "" : country);
  153. mVariant = "";
  154. }
  155. break;
  156. case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
  157. synchronized (this) {
  158. mLanguage = language;
  159. mCountry = ((country == null) ? "" : country);
  160. mVariant = ((variant == null) ? "" : variant);
  161. }
  162. break;
  163. case TextToSpeech.LANG_NOT_SUPPORTED:
  164. Log.e(TAG, "Unsupported language {language='" + language + "', country='" + country
  165. + "', variant='" + variant + "'}");
  166. break;
  167. }
  168. return result;
  169. }
  170. @Override
  171. protected void onStop() {
  172. Log.i(TAG, "Received stop request.");
  173. mEngine.stop();
  174. }
  175. @Override
  176. protected synchronized void onSynthesizeText(
  177. SynthesisRequest request, SynthesisCallback callback) {
  178. final int result = onLoadLanguage(request.getLanguage(), request.getCountry(), request.getVariant());
  179. switch (result) {
  180. case TextToSpeech.LANG_MISSING_DATA:
  181. case TextToSpeech.LANG_NOT_SUPPORTED:
  182. return;
  183. }
  184. String text = request.getText();
  185. if (text == null)
  186. return;
  187. final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  188. final String variantString = prefs.getString("espeak_variant", null);
  189. final SpeechSynthesis.VoiceVariant variant;
  190. if (variantString == null) {
  191. final int gender = getPreferenceValue(prefs, "default_gender", SpeechSynthesis.GENDER_MALE);
  192. if (gender == SpeechSynthesis.GENDER_FEMALE) {
  193. variant = SpeechSynthesis.parseVoiceVariant("default-female");
  194. } else {
  195. variant = SpeechSynthesis.parseVoiceVariant("default-male");
  196. }
  197. } else {
  198. variant = SpeechSynthesis.parseVoiceVariant(variantString);
  199. }
  200. int rate = getPreferenceValue(prefs, "espeak_rate", Integer.MIN_VALUE);
  201. if (rate == Integer.MIN_VALUE) {
  202. // Try the old eyes-free setting:
  203. int defaultValue = mEngine.Rate.getDefaultValue();
  204. int maxValue = mEngine.Rate.getMaxValue();
  205. rate = (getPreferenceValue(prefs, "default_rate", 100) / 100) * defaultValue;
  206. if (rate < defaultValue) rate = defaultValue;
  207. if (rate > maxValue) rate = maxValue;
  208. }
  209. int pitch = getPreferenceValue(prefs, "espeak_pitch", Integer.MIN_VALUE);
  210. if (pitch == Integer.MIN_VALUE) {
  211. // Try the old eyes-free setting:
  212. pitch = getPreferenceValue(prefs, "default_pitch", 100) / 2;
  213. }
  214. if (DEBUG) {
  215. Log.i(TAG, "Received synthesis request: {language=\"" + mMatchingVoice.name + "\"}");
  216. final Bundle params = request.getParams();
  217. for (String key : params.keySet()) {
  218. Log.v(TAG,
  219. "Synthesis request contained param {" + key + ", " + params.get(key) + "}");
  220. }
  221. }
  222. if (text.startsWith("<?xml"))
  223. {
  224. // eSpeak does not recognise/skip "<?...?>" preprocessing tags,
  225. // so need to remove these before passing to synthesize.
  226. text = text.substring(text.indexOf("?>") + 2).trim();
  227. }
  228. mCallback = callback;
  229. mCallback.start(mEngine.getSampleRate(), mEngine.getAudioFormat(),
  230. mEngine.getChannelCount());
  231. mEngine.setVoice(mMatchingVoice, variant);
  232. mEngine.Rate.setValue(rate, request.getSpeechRate());
  233. mEngine.Pitch.setValue(pitch, request.getPitch());
  234. mEngine.PitchRange.setValue(getPreferenceValue(prefs, "espeak_pitch_range", mEngine.PitchRange.getDefaultValue()));
  235. mEngine.Volume.setValue(getPreferenceValue(prefs, "espeak_volume", mEngine.Volume.getDefaultValue()));
  236. mEngine.synthesize(text, text.startsWith("<speak"));
  237. }
  238. private int getPreferenceValue(SharedPreferences prefs, String preference, int defaultValue) {
  239. final String prefString = prefs.getString(preference, null);
  240. if (prefString == null) {
  241. return defaultValue;
  242. }
  243. return Integer.parseInt(prefString);
  244. }
  245. /**
  246. * Pipes synthesizer output from native eSpeak to an {@link AudioTrack}.
  247. */
  248. private final SpeechSynthesis.SynthReadyCallback mSynthCallback = new SynthReadyCallback() {
  249. @Override
  250. public void onSynthDataReady(byte[] audioData) {
  251. if ((audioData == null) || (audioData.length == 0)) {
  252. onSynthDataComplete();
  253. return;
  254. }
  255. final int maxBytesToCopy = mCallback.getMaxBufferSize();
  256. int offset = 0;
  257. while (offset < audioData.length) {
  258. final int bytesToWrite = Math.min(maxBytesToCopy, (audioData.length - offset));
  259. mCallback.audioAvailable(audioData, offset, bytesToWrite);
  260. offset += bytesToWrite;
  261. }
  262. }
  263. @Override
  264. public void onSynthDataComplete() {
  265. mCallback.done();
  266. }
  267. };
  268. /**
  269. * Listens for language update broadcasts and initializes the eSpeak engine.
  270. */
  271. private BroadcastReceiver mBroadcastReceiver = null;
  272. }