65.9K
CodeProject 正在变化。 阅读更多。
Home

(通配符条目)Android 文本转语音合成,带有 Listview 数组和 toast

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4投票s)

2014年10月5日

CPOL

5分钟阅读

viewsIcon

24460

downloadIcon

370

(通配符条目)Android 文本转语音合成,带有 Listview 数组和 toast

引言

Bula Vinaka (您好),我叫 Prilvesh,来自斐济群岛。

作为 Android 比赛(通配符条目)的一部分,我写了一篇关于(TTS)合成的详细文章,但由于意外错误,文章从未发布。但我决心强调文本转语音合成的重要性,因此我再次写了一篇基础总结性指南。希望作为初学者,您会喜欢它。
 

本教程的目的是强调文本转语音合成(TTS)功能的重要性,该功能在相应的 Android 设备上可用。

文本转语音合成(TTS)是一个非常强大的工具,它常常被许多开发者所忽视,如果将其集成到您的应用程序中,可以增强用户体验,并为您的应用程序增添一定的优雅和精致感。

此外,从非常广泛的通用角度来看,TTS 对象实现的一个优势是它可以促进

  1. 迭代增量交互式活动
  2. 混合学习方法
  3. 将文本转换为合成音频,供盲人使用。
  4. 通过动态实现实时文本转语音合成,消除静态 mp3、mp4、ogg 格式,从而最大限度地减少平板电脑上使用的存储空间。
  5. 语言学习和发展以及语音发音的翻译。


Google text to speech settings


Android 上文本转语音合成(TTS)最棒的地方在于,作为初学者,它的实现非常容易,前提是您能从正确的信息渠道获得帮助。

因此,在本初学者教程中,我们将开发一个 Android Activity,允许您点击列表项,当列表项被点击时,文本会被朗读出来。

由于本教程的重点是初学者,我们将不实现任何错误检查。

具体来说,我们将

  1. 创建一个 Main Activity Java 类和相应的 XML 布局作为用户界面。
  2. 在 Main Activity Java 类中,我们将

 

  • 导入所需的 Activity 类,这些类通过扩展我们的 Activity 来实现 TTS 的初始化。
  • 创建一个 OnInitListener
  • 声明并创建一个静态元素的数组,用于填充 ListView 作为列表项。
  • 实现重写方法
  • 声明并初始化 TextToSpeech 对象,并指定基本参数。
  • 为列表项创建一个简单的 Array Adapter。
  • 实现一个 OnItemClickListener。
  • 最后,调用 TTS speak 函数,根据所选列表项的索引位置来朗读文本。

应用程序外观(基本列表)
Final application

使用代码

在本教程中,我们将使用 Eclipse IDE 和 ADT SDK 20。

我现在假设您已经安装了 IDE 和 Android SDK,但如果您还没有,请按照此链接中的步骤设置 Eclipse ADT 环境。

http://www.instructables.com/id/Building-Your-First-Android-Application/?ALLSTEPS

 

现在,真正的教程开始了。

要在您的 Activity 中使用TTS,您只需要导入android.speech.tts.TextToSpeech;import android.speech.tts.TextToSpeech.OnInitListener;

如果您想使用Toast,则需要导入 import android.widget.Toast;

因此,以下是我们为了扩展我们的 Activity 所需的类的完整列表。

import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

 

之前,我们只是列出了所有将要引用的头类。

现在,我们开始实际实现,创建一个名为 ListView App 的public class,它extends Activity 并实现OnInitListener

 

public class ListviewApp extends Activity implements OnInitListener
{
   public int index;

//we created an  interger  named index  which will be usefull to determine the position of our item.
   
 public String []words= {"Bula","Vinaka","moce mada","kaiviti","dua","rua"};

//we created a string array called words which contains our static listitems  The language is FIJIAN lol
    
public String [] pronounciation= {"Boola","Vinaka","More They Maandaa","Kaiviti","dooah","rooah"};

//For the fun of it we created a string array called pronounciation which contains pronounciations for our listitems
 
   @Override
    public void onCreate(Bundle savedInstanceState) //next we create our override method  which is onCreate

    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview_app);
//we basically set the view of this activity to our layout xml called  listview_app

        final ListView lv =(ListView) findViewById(R.id.List);
// now we call  our listview item called lv  

//Now here comes the main part  if you wish to use TTS  you need to initialize the TTS OBJECT:

        final TextToSpeech tts = new TextToSpeech(this,this);
// We declare a text to speech object with a variable name of tts
       
tts.setLanguage(Locale.ENGLISH); // We set the Language to English.

 //You can also Set Pitch, 1.0 is Normal   
//Lower values lower the tone of the synthesized voice, greater values increase it.
    tts.setPitch(0.8f);

    // You can also  Set Speech Rate, 1.0 is Normal
    //Lower values slow down the speech, greater values accelerate it
    tts.setSpeechRate(1.1f);

 

到目前为止,您已经创建了一个包含单词和发音的数组,并使用英语初始化了一个文本转语音对象。

接下来,让我们创建一个简单的适配器,它将单词数组填充到simple_list_item_1中。

ArrayAdapter array_adapter= new ArrayAdapter(this,
                                             android.R.layout.simple_list_item_1,android.R.id.text1,
                                             words);

lv.setAdapter(array_adapter); //We are mapping lv (listview) to  our array adapter 


 

现在让它工作起来到目前为止,我们的 Activity 只会显示一个列表,但点击时不会做任何事情。为了让它工作,我们需要创建一个 OnItemClickListener,当列表项被点击时,会完成三件事:首先,加载数组中对应的索引号位置;其次,生成一个 toast;最后,将文本转换为语音。

//we  are initializing our OnItemClickListener
 lv.setOnItemClickListener(new OnItemClickListener(){
 
        public void onItemClick(AdapterView<!--?--> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            index= arg2;
            
           
Toast.makeText(getApplicationContext(), words[index], Toast.LENGTH_SHORT).show(); 
//The item selected from the words array is toasted 
tts.speak(pronounciation[index], TextToSpeech.QUEUE_ADD, null);
//the item selected from the  pronouciation array is synthesized using the speak method.
           
            
tts.speak("haha man you just ran your first example ", TextToSpeech.QUEUE_ADD, null);
Toast.makeText(ListviewApp.this,"Become a friend www.facebook.com/prilvesh.k", Toast.LENGTH_LONG).show();}
 });
 } //just aword of advise becarefull of your curly brackets dont miss any !

之前,我们学习了如何创建一个 onlcik Listner 来检测哪个列表项被点击,并相应地将其值传递给我们的 Toast 方法 maketext 和 Text to speech synthesis 方法 tts。

恭喜,您的 ListviewApp.java 类现在可以正常工作了,但我们还没有完成。

最后,我们来创建一个 Override 方法来检查设备是否支持文本转语音合成。如果 TTS 功能不存在,将会出现错误,因此我们将通过 toast 来通知用户。
说实话,我们应该一开始就做这件事,但我们的主要重点是实现和使用。
 

 

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub
	      // we check to see if text to speech is suppourted on the device 
	      if (status == TextToSpeech.SUCCESS)
	      {
	          Toast.makeText(ListviewApp.this, 
	                  "Text-To-Speech SYNTHESIS engine is ready", Toast.LENGTH_SHORT).show();
	      }
	      
	      //If text to speech is not supported than we output an error message
	      else if (status== TextToSpeech.ERROR)
	      {
	     Toast.makeText(ListviewApp.this, 
	                  "Error occurred while initializing Text-To-Speech engine probably you dont have it installed", Toast.LENGTH_LONG).show();
	      }
		
	}

 

回顾(总结)

好了,您现在完成了!

但在您离开之前,用 3 个简单的步骤快速回顾一下实现文本转语音合成的方法:

步骤 1 - 导入头文件

import android.speech.tts.TextToSpeech;

import android.speech.tts.TextToSpeech.OnInitListener;

步骤 2 - 创建一个 tts 对象

final TextToSpeech tts = new TextToSpeech(this,this);

tts.setLanguage(Locale.ENGLISH);

步骤 3 - 从 onclick 监听器调用 speak 方法

tts.speak("THIS IS A TEXT TO SPEECH EXAMPLE THIS WILL BE SAID", TextToSpeech.QUEUE_FLUSH, null);

如果 XML 文件不显示,请下载源代码。

我们的 UI XML 文件名为:activity_listview_app.xml



    
    



 

我们的 Manifest 文件名为:AndroidManifest.xml

<!--?xml version="1.0" encoding="utf-8"?-->


    

    
        
            
                

                
            
        
    




 

最后,我们的 Activity 文件名为:ListviewApp.java

package com.example.listviewapp;

import java.util.Locale;


import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;




public class ListviewApp extends Activity implements OnInitListener
{
   public int index; 
// we created an  interger  named index  which will be usefull to determine the position of our item.
    public String []words= {"Bula","Vinaka","moce mada","kaiviti","dua","rua"};
//we created a string array called words which contains our static listitems  The language is FIJIAN lol
    public String [] pronounciation= {"Boola","Vinaka","More They Maandaa","Kaiviti","dooah","rooah"};
//For the fun of it we created a string array called pronounciation which contains pronounciations for our listitems
    @Override
    public void onCreate(Bundle savedInstanceState) //next we create our override method  which is onCreate

    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview_app); 
//we basically set the view of this activity to our layout xml called  listview_app

        final ListView lv =(ListView) findViewById(R.id.List);
 
        final TextToSpeech tts = new TextToSpeech(this,this);
        tts.setLanguage(Locale.ENGLISH);
        tts.setPitch(0.8f);
        tts.setSpeechRate(1.1f);
 
        ArrayAdapter array_adapter= new ArrayAdapter(this,
                                                          android.R.layout.simple_list_item_1,
                                                                     android.R.id.text1,
                                                                     words);
 
       lv.setAdapter(array_adapter);
 
       lv.setOnItemClickListener(new OnItemClickListener(){
 
        public void onItemClick(AdapterView<!--?--> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            index= arg2;
            
           
            Toast.makeText(getApplicationContext(), words[index], Toast.LENGTH_SHORT).show(); 
//The item selected from the words array is toasted 
            tts.speak(pronounciation[index], TextToSpeech.QUEUE_ADD, null);
//the item selected from the  pronouciation array is synthesized using the speak method.
           
            
           tts.speak("haha man you just ran your first example ", TextToSpeech.QUEUE_ADD, null);
           Toast.makeText(ListviewApp.this, 
	                  "Become a friend www.facebook.com/prilvesh.k", Toast.LENGTH_LONG).show();
        }
        
    });
 
      }

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub
	      // we check to see if text to speech is suppourted on the device 
	      if (status == TextToSpeech.SUCCESS)
	      {
	          Toast.makeText(ListviewApp.this, 
	                  "Text-To-Speech SYNTHESIS engine is ready", Toast.LENGTH_SHORT).show();
	      }
	      
	      //If text to speech is not supported than we output an error message
	      else if (status== TextToSpeech.ERROR)
	      {
	          Toast.makeText(ListviewApp.this, 
	                  "Error occurred while initializing Text-To-Speech engine probably you dont have it installed", Toast.LENGTH_LONG).show();
	      }
		
	}


}

关注点

如果您想深入了解 Fragments 和 Listviews 的教程,请参阅www.codeproject.com/Articles/820353/Create-an-app-for-Phone-and-Tablet

有关 TTS API 和功能的参考,请参阅https://developer.android.com.cn/reference/android/speech/tts/TextToSpeech.html

谢谢,结束!

© . All rights reserved.