pkrss used android phonegap tts plugin sample source follow:
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2011, IBM Corporation
*
* Modified by Murray Macdonald (murray@workgroup.ca) on 2012/05/30 to add support for stop(), pitch(), speed() and interrupt();
*
*/
package com.phonegap.plugins.speech;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import pk17s.cn.tts.R;
import pk17s.cn.KdxfTTS;
import pk17s.cn.PkrssActivity;
import pk17s.cn.PkrssPlugin;
public class TTS extends CordovaPlugin implements OnInitListener, OnUtteranceCompletedListener {
private static final String LOG_TAG = "TTS";
private static final int STOPPED = 0;
private static final int INITIALIZING = 1;
private static final int STARTED = 2;
public static TTS sTTS = null;
private TextToSpeech mTts = null;
private int state = STOPPED;
private String startupCallbackId = "";
private JSONArray lanauageList;
private KdxfTTS kdxfTTS;
int currentTTSType = 0; // 0:system 1:kdxftts
private HashMap<String,CallbackContext> Id2callbackContext = new HashMap<String,CallbackContext>();
private String saveCallbackContext(CallbackContext callbackContext){
String callbackId = callbackContext.getCallbackId();
Id2callbackContext.put(callbackId, callbackContext);
return callbackId;
}
private CallbackContext restoreCallbackContext(String callbackId){
CallbackContext callbackContext = Id2callbackContext.get(callbackId);
if(callbackContext!=null)
Id2callbackContext.remove(callbackId);
return callbackContext;
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("speak")) {
String text = args.getString(0);
if (isReady()) {
HashMap<String, String> map = null;
map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, saveCallbackContext(callbackContext));
mTts.speak(text, TextToSpeech.QUEUE_ADD, map);
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
} else {
JSONObject error = new JSONObject();
error.put("message","TTS service is still initialzing.");
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
} else if (action.equals("speakLanauageText")) {
if(args.getString(1).equals("System")){
currentTTSType = 0;
int available = mTts.setLanguage(new Locale(args.getString(0)));
if (isReady() && (available != TextToSpeech.LANG_MISSING_DATA) && (available != TextToSpeech.LANG_NOT_SUPPORTED)) {
HashMap<String, String> map = null;
map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, saveCallbackContext(callbackContext));
mTts.speak(args.getString(2), TextToSpeech.QUEUE_FLUSH, map);
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
}else if((kdxfTTS!=null) && (kdxfTTS.speakLanauageText(args.getString(0),args.getString(1),args.getString(2),callbackContext))){
currentTTSType = 1;
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
} else if (action.equals("speakLanauageTextToFile")) {
if(args.getString(1).equals("System")==false){
JSONObject error = new JSONObject();
error.put("message",PkrssActivity.s_pkrss.getString(R.string.error_notsupport_current) );
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
String filename = args.getString(3);
if(filename.length()==0){
filename = PkrssPlugin.getDownloadDir();
if(filename==""){
JSONObject error = new JSONObject();
error.put("message",PkrssActivity.s_pkrss.getString(R.string.error_openfile));
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
}
TTS.sTTS = this;
pk17s.cn.OnSaveFileLisnter listener = new pk17s.cn.OnSaveFileLisnter(){
JSONArray mArgs;
private String mcallbackId;
public void init(JSONArray args,String callbackId){
mArgs = args;
mcallbackId = callbackId;
}
public void OnOK(String theFilePath) {
// TODO Auto-generated method stub
try{
if(mArgs.getString(1).equals("System")){
int available = mTts.setLanguage(new Locale(mArgs.getString(0)));
if (isReady() && (available != TextToSpeech.LANG_MISSING_DATA) && (available != TextToSpeech.LANG_NOT_SUPPORTED)) {
HashMap<String, String> map = null;
map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mcallbackId);
mTts.synthesizeToFile(mArgs.getString(2), map, theFilePath);
return;
}
}else if((kdxfTTS!=null) && (kdxfTTS.speakLanauageTextToFile(mArgs.getString(0),mArgs.getString(1),mArgs.getString(2),restoreCallbackContext(mcallbackId)))){
sTTS.onUtteranceCompleted(mcallbackId);
return;
}
sTTS.onCancelCompleted(mcallbackId);
}catch (JSONException e) {
e.printStackTrace();
sTTS.onCancelCompleted(mcallbackId);
}
}
public void OnError() {
// TODO Auto-generated method stub
// onCancelCompleted
sTTS.onCancelCompleted(mcallbackId);
}
};
listener.init(args,saveCallbackContext(callbackContext));
PkrssActivity.s_pkrss.saveToFile(new File(filename),listener);
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
} else if (action.equals("setMute")) {
Boolean muted = args.getBoolean(0);
AudioManager am = (AudioManager)PkrssActivity.s_pkrss.getSystemService(Context.AUDIO_SERVICE);
if(muted)
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
else{
int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_RING);
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
am.setStreamVolume(AudioManager.STREAM_RING, maxVolume, AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);
}
callbackContext.success();
return true;
} else if (action.equals("setVolume")) {
int volume = args.getInt(0);
AudioManager am = (AudioManager)PkrssActivity.s_pkrss.getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_SYSTEM, volume, 0);
callbackContext.success();
return true;
} else if (action.equals("interrupt")) {
String text = args.getString(0);if (isReady()) {
HashMap<String, String> map = null;
map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, saveCallbackContext(callbackContext));
mTts.speak(text, TextToSpeech.QUEUE_FLUSH, map);
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
} else {
JSONObject error = new JSONObject();
error.put("message","TTS service is still initialzing.");
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
} else if (action.equals("stop")) {
if(currentTTSType==1){
if(kdxfTTS != null)
kdxfTTS.Stop();
callbackContext.success();
return true;
}
else if (isReady()) {
mTts.stop();
//if(mTts.isSpeaking()){
// mTts.speak("", TextToSpeech.QUEUE_FLUSH,new HashMap<String, String>());
//}
callbackContext.success();
return true;
} else {
JSONObject error = new JSONObject();
error.put("message","TTS service is still initialzing.");
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
} else if (action.equals("silence")) {
if (isReady()) {
mTts.playSilence(args.getLong(0), TextToSpeech.QUEUE_ADD, null);
callbackContext.success();
return true;
} else {
JSONObject error = new JSONObject();
error.put("message","TTS service is still initialzing.");
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
} else if (action.equals("speed")) {
if (isReady()) {
float speed= (float) (args.optLong(0, 100)) /(float) 100.0;
mTts.setSpeechRate(speed);
callbackContext.success();
return true;
} else {
JSONObject error = new JSONObject();
error.put("message","TTS service is still initialzing.");
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
} else if (action.equals("pitch")) {
if (isReady()) {
float pitch= (float) (args.optLong(0, 100)) /(float) 100.0;
mTts.setPitch(pitch);
callbackContext.success();
return true;
} else {
JSONObject error = new JSONObject();
error.put("message","TTS service is still initialzing.");
error.put("code", TTS.INITIALIZING);
callbackContext.error(error);
return true;
}
} else if (action.equals("startup")) {
if (mTts == null) {
this.startupCallbackId = saveCallbackContext(callbackContext);
state = TTS.INITIALIZING;
mTts = new TextToSpeech(cordova.getActivity().getApplicationContext(), this);
try{
//kdxfTTS = null;
kdxfTTS = new KdxfTTS(PkrssActivity.s_pkrss,this);
}catch(Exception e){
kdxfTTS = null;
}
}
PluginResult pluginResult = new PluginResult(status, TTS.INITIALIZING);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
else if (action.equals("shutdown")) {
if (mTts != null) {
mTts.shutdown();
}
callbackContext.success();
return true;
}
else if (action.equals("getLanguage")) {
if (mTts != null) {
result = mTts.getLanguage().toString();
callbackContext.sendPluginResult(new PluginResult(status, result));
return true;
}
}
else if (action.equals("getLanguageList")) {
if (lanauageList == null){
// if(args.getBoolean(0)){
lanauageList = new JSONArray();
for(int i=1;i<args.length();++i){
if(mTts != null){
String loc = args.getString(i);
Locale locale = new Locale(loc);
int available = mTts.setLanguage(locale);
if ((available == TextToSpeech.LANG_MISSING_DATA) || (available == TextToSpeech.LANG_NOT_SUPPORTED)) {
// Lanuage data is missing or the language is not supported.
Log.e(LOG_TAG, "Language is not available:"+loc);
//install it?
available = mTts.isLanguageAvailable(locale);
/*
if (available == TextToSpeech.LANG_AVAILABLE) {
AlertDialog.Builder builder = new AlertDialog.Builder(PkrssActivity.s_pkrss);
builder.setMessage("Language missing, install (" + loc + ") speech?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//installera
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
PkrssActivity.s_pkrss.startActivity(installIntent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
}
*/
//not installable
Log.e(LOG_TAG, "Language not installable:"+loc);
} else {
// The TTS engine has been successfully initialized.
JSONObject localeobject = new JSONObject();
JSONArray lanauages = new JSONArray();
JSONObject lanauage = new JSONObject();
lanauage.put("id", "System");lanauage.put("name", "System");
lanauages.put(lanauage);
localeobject.put("locale",loc);
localeobject.put("tts",lanauages);
localeobject.put("downloadCapable",true);
lanauageList.put(localeobject);
}
}
// Note that a language may not be available, and the result will indicate this.
}
if(kdxfTTS != null)
kdxfTTS.getLanauageList(lanauageList);
}
//Intent intent = new Intent();
//intent.setAction("android.speech.tts.engine.CHECK_TTS_DATA");
//intent.setClassName("com.android.settings", "com.android.settings.TextToSpeechSettings");
//PkrssActivity.s_pkrss.startActivity(intent);
// PkrssPlugin.openApp("com.android.settings","com.android.settings.TextToSpeechSettings");// "com.svox.pico"
callbackContext.sendPluginResult(new PluginResult(status, lanauageList));
return true;
}
else if (action.equals("isLanguageAvailable")) {
if (mTts != null) {
Locale loc = new Locale(args.getString(0));
int available = mTts.isLanguageAvailable(loc);
result = (available < 0) ? "false" : "true";
callbackContext.sendPluginResult(new PluginResult(status, result));
return true;
}
}
else if (action.equals("setLanguage")) {
if (mTts != null) {
Locale loc = new Locale(args.getString(0));
int available = mTts.setLanguage(loc);
result = (available < 0) ? "false" : "true";
callbackContext.sendPluginResult(new PluginResult(status, result));
return true;
}
}
callbackContext.success();
return true;
} catch (JSONException e) {
e.printStackTrace();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return true;
}
}
/**
* Is the TTS service ready to play yet?
*
* @return
*/
private boolean isReady() {
return (state == TTS.STARTED) ? true : false;
}
/**
* Called when the TTS service is initialized.
*
* @param status
*/
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
state = TTS.STARTED;
PluginResult result = new PluginResult(PluginResult.Status.OK, TTS.STARTED);
result.setKeepCallback(false);
restoreCallbackContext(this.startupCallbackId).sendPluginResult(result);
mTts.setOnUtteranceCompletedListener(this);
//int available = 0;
// available = mTts.setEngineByPackageName("com.iflytek.tts");
//Locale loc = mTts.getLanguage();
//mTts.setLanguage(Locale.CHINESE);
//loc = mTts.getLanguage();
//available = mTts.isLanguageAvailable(Locale.ENGLISH);
//available = mTts.isLanguageAvailable(Locale.US);
//available = mTts.isLanguageAvailable(Locale.CHINA);
//available = mTts.isLanguageAvailable(Locale.CHINESE);
//available = 0;
}
else if (status == TextToSpeech.ERROR) {
state = TTS.STOPPED;
PluginResult result = new PluginResult(PluginResult.Status.ERROR, TTS.STOPPED);
result.setKeepCallback(false);
restoreCallbackContext(this.startupCallbackId).sendPluginResult(result);
}
}
/**
* Clean up the TTS resources
*/
public void onDestroy() {
if (mTts != null) {
mTts.shutdown();
}
}
public void onStop()
{
if(mTts != null){
mTts.shutdown();
}
}
/**
* Once the utterance has completely been played call the speak's success callback
*/
public void onUtteranceCompleted(String utteranceId) {
PluginResult result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
restoreCallbackContext(utteranceId).sendPluginResult(result);
}
public void onCancelCompleted(String utteranceId) {
PluginResult result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
restoreCallbackContext(utteranceId).sendPluginResult(result);
}
}