码迷,mamicode.com
首页 > 移动开发 > 详细

android 中TextToSpeech的用法

时间:2015-03-13 00:35:08      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

目前只支持5种语言,分别是English French  German  Italian  Spanish.

系统要求为android 1.6以上

 

直接上代码啦:

 

[java] 

  1. public class TTSActivity extends Activity implements TextToSpeech.OnInitListener {  

  2.     private static final String TAG = "TextToSpeechDemo";  

private TextToSpeech mTts;//首先来个对象,至于TextToSpeech类,按F3可以查看

[java] 

  1. //TODO complete javadoc + add links to constants  

  2. public class TextToSpeech {  

  3.     /** 

  4.      * Denotes a successful operation. 

  5.      */  

  6.     public static final int SUCCESS                = 0;  

  7.     /** 

  8.      * Denotes a generic operation failure. 

  9.      */  

  10.     public static final int ERROR                  = -1;  

以上只包含部分代码,其他的就省略了。

[java]

  1. mTts = new TextToSpeech(this,  

  2.             this  // TextToSpeech.OnInitListener  

  3.             );  

然后是实例化,构造函数参数也可以F3一下

[java] 

  1. public TextToSpeech(Context context, OnInitListener listener) {  

  2.     mContext = context;  

  3.     mPackageName = mContext.getPackageName();  

  4.     mInitListener = listener;  

  5.     mCachedParams = new String[2*Engine.NB_CACHED_PARAMS]; // store key and value  

  6.     mCachedParams[Engine.PARAM_POSITION_RATE] = Engine.KEY_PARAM_RATE;  

  7.     mCachedParams[Engine.PARAM_POSITION_LANGUAGE] = Engine.KEY_PARAM_LANGUAGE;  

  8.     mCachedParams[Engine.PARAM_POSITION_COUNTRY] = Engine.KEY_PARAM_COUNTRY;  

  9.     mCachedParams[Engine.PARAM_POSITION_VARIANT] = Engine.KEY_PARAM_VARIANT;  

  10.     mCachedParams[Engine.PARAM_POSITION_STREAM] = Engine.KEY_PARAM_STREAM;  

  11.     mCachedParams[Engine.PARAM_POSITION_UTTERANCE_ID] = Engine.KEY_PARAM_UTTERANCE_ID;  

  12.     mCachedParams[Engine.PARAM_POSITION_RATE + 1] =  

  13.             String.valueOf(Engine.DEFAULT_RATE);  

  14.     // initialize the language cached parameters with the current Locale  

  15.     Locale defaultLoc = Locale.getDefault();  

  16.     mCachedParams[Engine.PARAM_POSITION_LANGUAGE + 1] = defaultLoc.getISO3Language();  

  17.     mCachedParams[Engine.PARAM_POSITION_COUNTRY + 1] = defaultLoc.getISO3Country();  

  18.     mCachedParams[Engine.PARAM_POSITION_VARIANT + 1] = defaultLoc.getVariant();  

  19.     mCachedParams[Engine.PARAM_POSITION_STREAM + 1] =  

  20.             String.valueOf(Engine.DEFAULT_STREAM);  

  21.     mCachedParams[Engine.PARAM_POSITION_UTTERANCE_ID + 1] = "";  

  22.     initTts();  

  23. }  

context也就是那个Activity

[java] 

  1. public abstract class Context {  

  2.     /** 

  3.      * File creation mode: the default mode, where the created file can only 

  4.      * be accessed by the calling application (or all applications sharing the 

  5.      * same user ID). 

  6.      * @see #MODE_WORLD_READABLE 

  7.      * @see #MODE_WORLD_WRITEABLE 

  8.      */  

  9.     public static final int MODE_PRIVATE = 0x0000;  

  10.     /** 

  11.      * File creation mode: allow all other applications to have read access 

  12.      * to the created file. 

  13.      * @see #MODE_PRIVATE 

  14.      * @see #MODE_WORLD_WRITEABLE 

  15.      */  

  16.     public static final int MODE_WORLD_READABLE = 0x0001;  

  17.     /** 

  18.      * File creation mode: allow all other applications to have write access 

  19.      * to the created file. 

  20.      * @see #MODE_PRIVATE 

  21.      * @see #MODE_WORLD_READABLE 

  22.      */  

listener是个初始化监听接口

[java]

  1. /** 

  2.      * Called when the TTS has initialized. 

  3.      * 

  4.      * The InitListener must implement the onInit function. onInit is passed a 

  5.      * status code indicating the result of the TTS initialization. 

  6.      */  

  7.     public interface OnInitListener {  

  8.         public void onInit(int status);  

  9.     }  

 

implements Listener代码如下:(这是APIDemo里面的)

[java] 

  1. // Implements TextToSpeech.OnInitListener.  

  2.     public void onInit(int status) {  

  3.         // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.  

  4.         if (status == TextToSpeech.SUCCESS) {  

  5.             // Set preferred language to US english.  

  6.             // Note that a language may not be available, and the result will indicate this.  

  7.             int result = mTts.setLanguage(Locale.US);  

  8.             // Try this someday for some interesting results.  

  9.             // int result mTts.setLanguage(Locale.FRANCE);  

  10.             if (result == TextToSpeech.LANG_MISSING_DATA ||  

  11.                 result == TextToSpeech.LANG_NOT_SUPPORTED) {  

  12.                // Lanuage data is missing or the language is not supported.  

  13.                 Log.e(TAG, "Language is not available.");  

  14.             } else {  

  15.                 // Check the documentation for other possible result codes.  

  16.                 // For example, the language may be available for the locale,  

  17.                 // but not for the specified country and variant.  

  18.                 // The TTS engine has been successfully initialized.  

  19.                 // Allow the user to press the button for the app to speak again.  

  20.                 mAgainButton.setEnabled(true);  

  21.                 // Greet the user.  

  22.                 sayHello();  

  23.             }  

  24.         } else {  

  25.             // Initialization failed.  

  26.             Log.e(TAG, "Could not initialize TextToSpeech.");  

  27.         }  

  28.     }  

status这个在构造函数中赋值,(Ctrl+F可以在源码中找到)

 

[java] 

  1.     mCachedParams[Engine.PARAM_POSITION_STREAM + 1] =  

  2.             String.valueOf(Engine.DEFAULT_STREAM);  

  3.     mCachedParams[Engine.PARAM_POSITION_UTTERANCE_ID + 1] = "";  

  4.     initTts();//构造函数最后这个地方  

  5. }  

  6.   

  7. private void initTts() {  

  8.     mStarted = false;  

  9.     // Initialize the TTS, run the callback after the binding is successful  

  10.     mServiceConnection = new ServiceConnection() {  

  11.         public void onServiceConnected(ComponentName name, IBinder service) {  

  12.             synchronized(mStartLock) {  

  13.                 mITts = ITts.Stub.asInterface(service);  

  14.                 mStarted = true;  

  15.                 if (mInitListener != null) {  

  16.                     // TODO manage failures and missing resources  

  17.                     mInitListener.onInit(SUCCESS);//这里给status赋值  

  18.                 }  

  19.             }  

  20.         }  

 

 

setLanguage方法源码:

[java] 

  1. public int setLanguage(Locale loc) {  

  2.        synchronized (mStartLock) {  

  3.            int result = LANG_NOT_SUPPORTED;  

  4.            if (!mStarted) {  

  5.                return result;  

  6.            }  

  7.            try {  

  8.                mCachedParams[Engine.PARAM_POSITION_LANGUAGE + 1] = loc.getISO3Language();  

  9.                mCachedParams[Engine.PARAM_POSITION_COUNTRY + 1] = loc.getISO3Country();  

  10.                mCachedParams[Engine.PARAM_POSITION_VARIANT + 1] = loc.getVariant();  

  11.                // the language is not set here, instead it is cached so it will be associated  

  12.                // with all upcoming utterances. But we still need to report the language support,  

  13.                // which is achieved by calling isLanguageAvailable()  

  14.                result = mITts.isLanguageAvailable(  

  15.                        mCachedParams[Engine.PARAM_POSITION_LANGUAGE + 1],  

  16.                        mCachedParams[Engine.PARAM_POSITION_COUNTRY + 1],  

  17.                        mCachedParams[Engine.PARAM_POSITION_VARIANT + 1] );  

  18.            } catch (RemoteException e) {  

  19.                // TTS died; restart it.  

  20.                Log.e("TextToSpeech.java - setLanguage""RemoteException");  

  21.                e.printStackTrace();  

  22.                mStarted = false;  

  23.                initTts();  

  24.            } catch (NullPointerException e) {  

  25.                // TTS died; restart it.  

  26.                Log.e("TextToSpeech.java - setLanguage""NullPointerException");  

  27.                e.printStackTrace();  

  28.                mStarted = false;  

  29.                initTts();  

  30.            } catch (IllegalStateException e) {  

  31.                // TTS died; restart it.  

  32.                Log.e("TextToSpeech.java - setLanguage""IllegalStateException");  

  33.                e.printStackTrace();  

  34.                mStarted = false;  

  35.                initTts();  

  36.            } finally {  

  37.              return result;  

  38.            }  

  39.        }  

  40.    }  

Locale.US定义如下:

[java] 

  1. public static final Locale UK = new Locale("en""GB"); //$NON-NLS-1$ //$NON-NLS-2$  

  2. /** 

  3.  * Locale constant for en_US. 

  4.  *  

  5.  * @since Android 1.0 

  6.  */  

  7. public static final Locale US = new Locale("en""US");  //$NON-NLS-1$//$NON-NLS-2$  

Locale构造器源码:

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_11 name=ZeroClipboardMovie_11 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=11&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. /** 

  2.  * Constructs a new {@code Locale} using the specified language and country codes. 

  3.  *  

  4.  * @param language 

  5.  *            the language this {@code Locale} represents. 

  6.  * @param country 

  7.  *            the country this {@code Locale} represents. 

  8.  * @since Android 1.0 

  9.  */  

  10. public Locale(String language, String country) {  

  11.     this(language, country, ""); //$NON-NLS-1$  

  12. }  

这里每按一次按钮就有一个Speech

[java]

  1. private void sayHello() {  

  2.     String left = "Please turn left";  

  3.     String right="Please turn right";  

  4.     if(mDirection==0){  

  5.         mTts.speak(left,  

  6.         TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.  

  7.         null);  

  8.         mDirection=1;  

  9.     }else{  

  10.         mTts.speak(right, TextToSpeech.QUEUE_FLUSH, null);  

  11.         mDirection=0;  

  12.     }  

  

speak函数源码:各参数都有相应的解释,我就不啰嗦了

[java]

  1. /** 

  2.  * Speaks the string using the specified queuing strategy and speech 

  3.  * parameters. Note that the speech parameters are not universally supported 

  4.  * by all engines and will be treated as a hint. The TTS library will try to 

  5.  * fulfill these parameters as much as possible, but there is no guarantee 

  6.  * that the voice used will have the properties specified. 

  7.  * 

  8.  * @param text 

  9.  *            The string of text to be spoken. 

  10.  * @param queueMode 

  11.  *            The queuing strategy to use. 

  12.  *            See QUEUE_ADD and QUEUE_FLUSH. 

  13.  * @param params 

  14.  *            The hashmap of speech parameters to be used. 

  15.  * 

  16.  * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 

  17.  */  

  18. public int speak(String text, int queueMode, HashMap<String,String> params)  

  19. {  

  20.     synchronized (mStartLock) {  

  21.         int result = ERROR;  

  22.         Log.i("TTS received: ", text);  

  23.         if (!mStarted) {  

  24.             return result;  

  25.         }  

  26.         try {  

  27.             if ((params != null) && (!params.isEmpty())) {  

  28.                 String extra = params.get(Engine.KEY_PARAM_STREAM);  

  29.                 if (extra != null) {  

  30.                     mCachedParams[Engine.PARAM_POSITION_STREAM + 1] = extra;  

  31.                 }  

  32.                 extra = params.get(Engine.KEY_PARAM_UTTERANCE_ID);  

  33.                 if (extra != null) {  

  34.                     mCachedParams[Engine.PARAM_POSITION_UTTERANCE_ID + 1] = extra;  

  35.                 }  

  36.             }  

  37.             result = mITts.speak(mPackageName, text, queueMode, mCachedParams);  

  38.         } catch (RemoteException e) {  

  39.             // TTS died; restart it.  

  40.             Log.e("TextToSpeech.java - speak""RemoteException");  

  41.             e.printStackTrace();  

  42.             mStarted = false;  

  43.             initTts();  

  44.         } catch (NullPointerException e) {  

  45.             // TTS died; restart it.  

  46.             Log.e("TextToSpeech.java - speak""NullPointerException");  

  47.             e.printStackTrace();  

  48.             mStarted = false;  

  49.             initTts();  

  50.         } catch (IllegalStateException e) {  

  51.             // TTS died; restart it.  

  52.             Log.e("TextToSpeech.java - speak""IllegalStateException");  

  53.             e.printStackTrace();  

  54.             mStarted = false;  

  55.             initTts();  

  56.         } finally {  

  57.             resetCachedParams();  

  58.             return result;  

  59.         }  

  60.     }  

  61. }  

还有在Activity退出时作一些操作

[java] 

  1. @Override  

  2. public void onDestroy() {  

  3.     // Don‘t forget to shutdown!  

  4.     if (mTts != null) {  

  5.         mTts.stop();  

  6.         mTts.shutdown();  

  7.     }  

  8.     super.onDestroy();  

  9. }  

能看到源码真好...深入学习...呵呵

我们再看下android 到底是怎样stop和shutdown的

[java] view plaincopy

<EMBED id=ZeroClipboardMovie_15 name=ZeroClipboardMovie_15 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer height=18 width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=15&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. /** 

  2.      * Stops speech from the TTS. 

  3.      * 

  4.      * @return Code indicating success or failure. See {@link #ERROR} and {@link #SUCCESS}. 

  5.      */  

  6.     public int stop() {  

  7.         synchronized (mStartLock) {  

  8.             int result = ERROR;  

  9.             if (!mStarted) {  

  10.                 return result;  

  11.             }  

  12.             try {  

  13.                 result = mITts.stop(mPackageName);  

  14.             } catch (RemoteException e) {  

  15.                 // TTS died; restart it.  

  16.                 Log.e("TextToSpeech.java - stop""RemoteException");  

  17.                 e.printStackTrace();  

  18.                 mStarted = false;  

  19.                 initTts();  

  20.             } catch (NullPointerException e) {  

  21.                 // TTS died; restart it.  

  22.                 Log.e("TextToSpeech.java - stop""NullPointerException");  

  23.                 e.printStackTrace();  

  24.                 mStarted = false;  

  25.                 initTts();  

  26.             } catch (IllegalStateException e) {  

  27.                 // TTS died; restart it.  

  28.                 Log.e("TextToSpeech.java - stop""IllegalStateException");  

  29.                 e.printStackTrace();  

  30.                 mStarted = false;  

  31.                 initTts();  

  32.             } finally {  

  33.               return result;  

  34.             }  

  35.         }  

  36.     }  

还有shutdown函数:

[java] 

  1. /** 

  2.  * Shuts down the TTS. It is good practice to call this in the onDestroy 

  3.  * method of the Activity that is using the TTS so that the TTS is stopped 

  4.  * cleanly. 

  5.  */  

  6. public void shutdown() {  

  7.     try {  

  8.         mContext.unbindService(mServiceConnection);  

  9.     } catch (IllegalArgumentException e) {  

  10.         // Do nothing and fail silently since an error here indicates that  

  11.         // binding never succeeded in the first place.  

  12.     }  

  13. }  

 

还有Activity的destroy函数:

[java] 

  1. /** 

  2.  * Perform any final cleanup before an activity is destroyed.  This can 

  3.  * happen either because the activity is finishing (someone called 

  4.  * {@link #finish} on it, or because the system is temporarily destroying 

  5.  * this instance of the activity to save space.  You can distinguish 

  6.  * between these two scenarios with the {@link #isFinishing} method. 

  7.  *  

  8.  * <p><em>Note: do not count on this method being called as a place for 

  9.  * saving data! For example, if an activity is editing data in a content 

  10.  * provider, those edits should be committed in either {@link #onPause} or 

  11.  * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to 

  12.  * free resources like threads that are associated with an activity, so 

  13.  * that a destroyed activity does not leave such things around while the 

  14.  * rest of its application is still running.  There are situations where 

  15.  * the system will simply kill the activity‘s hosting process without 

  16.  * calling this method (or any others) in it, so it should not be used to 

  17.  * do things that are intended to remain around after the process goes 

  18.  * away. 

  19.  *  

  20.  * <p><em>Derived classes must call through to the super class‘s 

  21.  * implementation of this method.  If they do not, an exception will be 

  22.  * thrown.</em></p> 

  23.  *  

  24.  * @see #onPause 

  25.  * @see #onStop 

  26.  * @see #finish 

  27.  * @see #isFinishing 

  28.  */  

  29. protected void onDestroy() {  

  30.     mCalled = true;  

  31.     // dismiss any dialogs we are managing.  

  32.     if (mManagedDialogs != null) {  

  33.         final int numDialogs = mManagedDialogs.size();  

  34.         for (int i = 0; i < numDialogs; i++) {  

  35.             final Dialog dialog = mManagedDialogs.valueAt(i);  

  36.             if (dialog.isShowing()) {  

  37.                 dialog.dismiss();  

  38.             }  

  39.         }  

  40.     }  

  41.     // close any cursors we are managing.  

  42.     int numCursors = mManagedCursors.size();  

  43.     for (int i = 0; i < numCursors; i++) {  

  44.         ManagedCursor c = mManagedCursors.get(i);  

  45.         if (c != null) {  

  46.             c.mCursor.close();  

  47.         }  

  48.     }  

  49. }  

 

好了,这个TTS就到这里。

至于现在到底是否支持中文发音这个我还没调查过。实在不行的话我们就做English版的软件也不错,单词发音,语音导航等等都是可以运用TTS的。

还有再唠叨一下,最近居然看到源码了,爽YY呀。感觉这一步就像是从了解一个人的表面到了解其本质...从上到下,从外到内...

 

android 中TextToSpeech的用法

标签:

原文地址:http://my.oschina.net/airship/blog/386423

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!