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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 java.util.List;
  40. import java.util.Locale;
  41. /**
  42. * Implements the eSpeak engine as a {@link TextToSpeechService}.
  43. *
  44. * @author [email protected] (Reece H. Dunn)
  45. * @author [email protected] (Alan Viverette)
  46. */
  47. @SuppressLint("NewApi")
  48. public class TtsService extends TextToSpeechService {
  49. private static final String TAG = TtsService.class.getSimpleName();
  50. private static final boolean DEBUG = false;
  51. private static final String DEFAULT_LANGUAGE = "en";
  52. private static final String DEFAULT_COUNTRY = "uk";
  53. private static final String DEFAULT_VARIANT = "";
  54. private SpeechSynthesis mEngine;
  55. private SynthesisCallback mCallback;
  56. private List<Voice> mAvailableVoices;
  57. private Voice mMatchingVoice = null;
  58. private BroadcastReceiver mOnLanguagesDownloaded = 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 (mOnLanguagesDownloaded != null) {
  71. unregisterReceiver(mOnLanguagesDownloaded);
  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 (mOnLanguagesDownloaded == null) {
  96. mOnLanguagesDownloaded = 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(mOnLanguagesDownloaded, 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(mLanguage, mCountry, mVariant);
  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. if (DEBUG) {
  188. Log.i(TAG, "Received synthesis request: {language=\"" + mMatchingVoice.name + "\"}");
  189. final Bundle params = request.getParams();
  190. for (String key : params.keySet()) {
  191. Log.v(TAG,
  192. "Synthesis request contained param {" + key + ", " + params.get(key) + "}");
  193. }
  194. }
  195. if (text.startsWith("<?xml"))
  196. {
  197. // eSpeak does not recognise/skip "<?...?>" preprocessing tags,
  198. // so need to remove these before passing to synthesize.
  199. text = text.substring(text.indexOf("?>") + 2).trim();
  200. }
  201. mCallback = callback;
  202. mCallback.start(mEngine.getSampleRate(), mEngine.getAudioFormat(), mEngine.getChannelCount());
  203. final VoiceSettings settings = new VoiceSettings(PreferenceManager.getDefaultSharedPreferences(this), mEngine);
  204. mEngine.setVoice(mMatchingVoice, settings.getVoiceVariant());
  205. mEngine.Rate.setValue(settings.getRate(), request.getSpeechRate());
  206. mEngine.Pitch.setValue(settings.getPitch(), request.getPitch());
  207. mEngine.PitchRange.setValue(settings.getPitchRange());
  208. mEngine.Volume.setValue(settings.getVolume());
  209. mEngine.synthesize(text, text.startsWith("<speak"));
  210. }
  211. /**
  212. * Pipes synthesizer output from native eSpeak to an {@link AudioTrack}.
  213. */
  214. private final SpeechSynthesis.SynthReadyCallback mSynthCallback = new SynthReadyCallback() {
  215. @Override
  216. public void onSynthDataReady(byte[] audioData) {
  217. if ((audioData == null) || (audioData.length == 0)) {
  218. onSynthDataComplete();
  219. return;
  220. }
  221. final int maxBytesToCopy = mCallback.getMaxBufferSize();
  222. int offset = 0;
  223. while (offset < audioData.length) {
  224. final int bytesToWrite = Math.min(maxBytesToCopy, (audioData.length - offset));
  225. mCallback.audioAvailable(audioData, offset, bytesToWrite);
  226. offset += bytesToWrite;
  227. }
  228. }
  229. @Override
  230. public void onSynthDataComplete() {
  231. mCallback.done();
  232. }
  233. };
  234. }