文字转语音(TTS)-Android

Posted

技术标签:

【中文标题】文字转语音(TTS)-Android【英文标题】:Text to speech(TTS)-Android 【发布时间】:2011-03-04 18:54:55 【问题描述】:

我是安卓平台的新手。现在我正在处理TTS(Text to Speech)。如果我在 TextArea 中输入文本,并且我希望在单击发言按钮时将其转换为语音。

谁能帮帮我?

【问题讨论】:

【参考方案1】:

文字转语音内置于 android 1.6+ 中。这是一个简单的例子。

TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);

更多信息:http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html


Here are instructions关于如何从 Android SDK 管理器下载示例代码:

    启动 Android SDK 管理器。

    一个。在 Windows 上,双击 Android SDK 目录根目录下的 SDK Manager.exe 文件。

    b.在 Mac 或 Linux 上,打开终端到 Android SDK 中的 tools/ 目录,然后执行 android sdk。

    展开最新 Android 平台的软件包列表。

    选择并下载 SDK 示例。 下载完成后,您可以在此位置找到所有示例的源代码:

/sdk/samples/android-version/

(i.e. \android-sdk-windows\samples\android-16\ApiDemos\src\com\example\android\apis\app\TextToSpeechActivity.java)

【讨论】:

+1 用于指出每个平台版本的最佳方法。 SDK 示例。 我得到的 speak 目前已弃用 因为没有被弃用的是:speak(CharSequence text, int queueMode, Bundle params, String utteranceId) 您必须等待 TTS 初始化。 要导入的西班牙语和土耳其语以及其他语言呢?【参考方案2】:

MainActivity.class

import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity 

    String text;
    EditText et;
    TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et=(EditText)findViewById(R.id.editText1);
        tts=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() 

            @Override
            public void onInit(int status) 
                // TODO Auto-generated method stub
                if(status == TextToSpeech.SUCCESS)
                    int result=tts.setLanguage(Locale.US);
                    if(result==TextToSpeech.LANG_MISSING_DATA ||
                            result==TextToSpeech.LANG_NOT_SUPPORTED)
                        Log.e("error", "This Language is not supported");
                    
                    else
                        ConvertTextToSpeech();
                    
                
                else
                    Log.e("error", "Initilization Failed!");
            
        );


    

    @Override
    protected void onPause() 
        // TODO Auto-generated method stub

        if(tts != null)

            tts.stop();
            tts.shutdown();
        
        super.onPause();
    

    public void onClick(View v)

        ConvertTextToSpeech();

    

    private void ConvertTextToSpeech() 
        // TODO Auto-generated method stub
        text = et.getText().toString();
        if(text==null||"".equals(text))
        
            text = "Content not available";
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        else
            tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
    


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_
        android:layout_
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="177dp"
        android:onClick="onClick"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_
        android:layout_
        android:layout_alignBottom="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="81dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout>

【讨论】:

这是一个更完整的例子。它包括接受的答案中缺少的 TextToSpeech.OnInitListener 的实现。好东西! +1 感谢这些好东西!! +1 .. 但是,如果我使用 1000 多个单词(听起来像 PDF),我可以用“恢复”选项实现“播放”和“暂停”吗? tts.shutdown() 应该移到 onDestroy() 方法中。【参考方案3】:

快速测试 TTS 系统的简约示例:

private TextToSpeech textToSpeechSystem;

@Override
protected void onStart() 
  super.onStart();
  textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() 
        @Override
        public void onInit(int status) 
            if (status == TextToSpeech.SUCCESS) 
                String textToSay = "Hello world, this is a test message!";
                textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
            
        
   );

如果您不使用本地化消息,textToSpeechSystem.setLanguage(..) 也很重要,因为您的用户可能并非都将英语设置为默认语言,因此单词的发音会出错。但是对于一般的 TTS 测试来说,这个 sn-p 就足够了

相关链接:https://developer.android.com/reference/android/speech/tts/TextToSpeech

【讨论】:

【参考方案4】:

试试这个,很简单: **speakout.xml:**

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_
android:layout_
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_/>
<Button
android:id="@+id/btnspeakout"
android:layout_
android:layout_
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>

还有你的 SpeakOut.java :

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.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener 
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speakout);
    btnspeakout = (Button) findViewById(R.id.btnspeakout);
    edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
    repeatTTS = new TextToSpeech(this, this);
    btnspeakout.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            repeatTTS.speak(edtTexttoSpeak.getText().toString(),
            TextToSpeech.QUEUE_FLUSH, null);
        
    );


@Override
    public void onInit(int arg0) 
        // TODO Auto-generated method stub
    

来源Parallelcodes.com's Post

【讨论】:

【参考方案5】:
public class Texttovoice extends ActionBarActivity implements OnInitListener 
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_texttovoice);
    tts = new TextToSpeech(this, this);

    // Refer 'Speak' button
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    // Refer 'Text' control
    txtText = (EditText) findViewById(R.id.txtText);
    // Handle onClick event for button 'Speak'
    btnSpeak.setOnClickListener(new View.OnClickListener() 

        public void onClick(View arg0) 
            // Method yet to be defined
            speakOut();
        

    );



private void speakOut() 
    // Get the text typed
    String text = txtText.getText().toString();
    // If no text is typed, tts will read out 'You haven't typed text'
    // else it reads out the text you typed
    if (text.length() == 0) 
        tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
     else 
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

    



public void onDestroy() 
    // Don't forget to shutdown!
    if (tts != null) 
        tts.stop();
        tts.shutdown();
    
    super.onDestroy();


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.texttovoice, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) 
        return true;
    
    return super.onOptionsItemSelected(item);


public void onInit(int status) 
    // TODO Auto-generated method stub
    // TTS is successfully initialized
    if (status == TextToSpeech.SUCCESS) 
        // Setting speech language
        int result = tts.setLanguage(Locale.US);
        // If your device doesn't support language you set above
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) 
            // Cook simple toast message with message
            Toast.makeText(getApplicationContext(), "Language not supported",
                    Toast.LENGTH_LONG).show();
            Log.e("TTS", "Language is not supported");
        
        // Enable the button - It was disabled in main.xml (Go back and
        // Check it)
        else 
            btnSpeak.setEnabled(true);
        
        // TTS is not initialized properly
     else 
        Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
                .show();
        Log.e("TTS", "Initilization Failed");
    

   //-------------------------------XML---------------

  <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText" >

    <TextView
    android:layout_
    android:layout_
    android:gravity="center"
    android:padding="15dip"
    android:text="listen your text"
    android:textColor="#0587d9"
    android:textSize="26dip"
    android:textStyle="bold" />

<EditText
    android:id="@+id/txtText"
    android:layout_
    android:layout_
    android:layout_margin="10dip"
    android:layout_marginTop="20dip"
    android:hint="Enter text to speak" />

<Button
    android:id="@+id/btnSpeak"
    android:layout_
    android:layout_
    android:layout_margin="10dip"
    android:enabled="false"
    android:text="Speak" 
    android:onClick="speakout"/>

【讨论】:

【参考方案6】:
// variable declaration
TextToSpeech tts;

// TextToSpeech initialization, must go within the onCreate method
tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() 
 @Override
 public void onInit(int i) 
  if (i == TextToSpeech.SUCCESS) 
   int result = tts.setLanguage(Locale.US);
   if (result == TextToSpeech.LANG_MISSING_DATA ||
    result == TextToSpeech.LANG_NOT_SUPPORTED) 
    Log.e("TTS", "Lenguage not supported");
   
   else 
   Log.e("TTS", "Initialization failed");
  
 
);

// method call
public void buttonSpeak().setOnClickListener(new View.OnClickListener() 
 @Override
 public void onClick(View view) 
  speak();
 
);


private void speak() 
 tts.speak("Text to Speech Test", TextToSpeech.QUEUE_ADD, null);


@Override
public void onDestroy() 
 if (tts != null) 
  tts.stop();
  tts.shutdown();
 
 super.onDestroy();

取自:Text to Speech Youtube Tutorial

【讨论】:

【参考方案7】:

https://drive.google.com/open?id=0BzBKpZ4nzNzUR05nVUI1aVF6N1k

package com.keshav.speechtotextexample;

import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity 

   private TextView txtSpeechInput;
   private ImageButton btnSpeak;
   private final int REQ_CODE_SPEECH_INPUT = 100;

   @Override
   protected void onCreate(Bundle savedInstanceState) 
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
      btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

      // hide the action bar
      getActionBar().hide();

      btnSpeak.setOnClickListener(new View.OnClickListener() 

         @Override
         public void onClick(View v) 
            promptSpeechInput();
         
      );

   

   /**
    * Showing google speech input dialog
    * */
   private void promptSpeechInput() 
      Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
      intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
      intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
      intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
      try 
         startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
       catch (ActivityNotFoundException a) 
         Toast.makeText(getApplicationContext(),
               getString(R.string.speech_not_supported),
               Toast.LENGTH_SHORT).show();
      
   

   /**
    * Receiving speech input
    * */
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) 
      super.onActivityResult(requestCode, resultCode, data);

      switch (requestCode) 
      case REQ_CODE_SPEECH_INPUT: 
         if (resultCode == RESULT_OK && null != data) 

            ArrayList<String> result = data
                  .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            txtSpeechInput.setText(result.get(0));
         
         break;
      

      
   

   @Override
   public boolean onCreateOptionsMenu(Menu menu) 
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   




====================================================

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:background="@drawable/bg_gradient"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtSpeechInput"
        android:layout_
        android:layout_
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:textColor="@color/white"
        android:textSize="26dp"
        android:textStyle="normal" />

    <LinearLayout
        android:layout_
        android:layout_
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="60dp"
        android:gravity="center"
        android:orientation="vertical">

        <ImageButton
            android:id="@+id/btnSpeak"
            android:layout_
            android:layout_
            android:background="@null"
            android:src="@drawable/ico_mic" />

        <TextView
            android:layout_
            android:layout_
            android:layout_marginTop="10dp"
            android:text="@string/tap_on_mic"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:textStyle="normal" />
    </LinearLayout>

</RelativeLayout>
===============================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Speech To Text</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="speech_prompt">Say something&#8230;</string>
    <string name="speech_not_supported">Sorry! Your device doesn\'t support speech input</string>
    <string name="tap_on_mic">Tap on mic to speak</string>

</resources>
===============================================================
<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

【讨论】:

【参考方案8】:
    package com.example.text_to_speech;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Toast;

import com.example.fyp.R;

import java.util.Locale;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class textTospeech_class extends AppCompatActivity 
    TextToSpeech textToSpeech;
    String text;
    int result;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_tospeech);
        textToSpeech = new TextToSpeech(textTospeech_class.this, new TextToSpeech.OnInitListener() 
            @Override
            public void onInit(int i) 
                if (i == TextToSpeech.SUCCESS) 
                    result = textToSpeech.setLanguage(Locale.ENGLISH);
                 else 
                    Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
                

            
        );
    
    public void tts(View view)
    
        switch (view.getId()) 
            case R.id.speechid:
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) 
                    Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();

                 else 
                    textToSpeech.speak("a for apple", TextToSpeech.QUEUE_FLUSH, null);
                
                break;
            case R.id.bid:
            
                if(result==TextToSpeech.LANG_MISSING_DATA || result== TextToSpeech.LANG_NOT_SUPPORTED)
                
                    Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();

                
                else
                
                    textToSpeech.speak("b for ball",TextToSpeech.QUEUE_FLUSH,null);
                
                break;
            

【讨论】:

以上是关于文字转语音(TTS)-Android的主要内容,如果未能解决你的问题,请参考以下文章

chrome文字转语音(tts)

chrome文字转语音(tts)

Android文字转语音引擎(TTS)使用

Android实现TTS文字转语音功能

Android实现TTS文字转语音功能

Android实现TTS文字转语音功能