Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
文本到语音(TTS)-Android_Android_Text To Speech - Fatal编程技术网

文本到语音(TTS)-Android

文本到语音(TTS)-Android,android,text-to-speech,Android,Text To Speech,我是android平台的新手。现在我正在使用TTS(文本到语音)。如果我在文本区域中输入文本,并希望在单击speak按钮时将其转换为语音 有人能帮我吗?Android 1.6+内置了文本到语音转换功能。下面是一个简单的例子来说明如何做到这一点 TextToSpeech tts = new TextToSpeech(this, this); tts.setLanguage(Locale.US); tts.speak("Text to say aloud", TextToSpeech.QUEUE_A

我是android平台的新手。现在我正在使用
TTS(文本到语音)
。如果我在文本区域中输入文本,并希望在单击speak按钮时将其转换为语音


有人能帮我吗?

Android 1.6+内置了文本到语音转换功能。下面是一个简单的例子来说明如何做到这一点

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


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

  • 启动Android SDK管理器

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

    b。在Mac或Linux上,打开Android SDK中工具/目录的终端,然后执行Android SDK

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

  • 选择并下载SDK示例。 下载完成后,您可以在以下位置找到所有示例的源代码:
  • /sdk/samples/android版本/

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

    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);
        }
    
    }
    
    活动\u main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        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_width="wrap_content"
            android:layout_height="wrap_content"
            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_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/button1"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="81dp"
            android:ems="10" >
    
            <requestFocus />
        </EditText>
    
    </RelativeLayout>
    
    
    
    公共类Texttovoice扩展了ActionBarActivity在NitListener上实现{
    私密文本语音tts;
    专用按钮btnSpeak;
    私有EditText-txtText;
    @凌驾
    创建时受保护的void(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_texttovoice);
    tts=新的TextToSpeech(这个,这个);
    //请参阅“讲话”按钮
    btnSpeak=(按钮)findViewById(R.id.btnSpeak);
    //请参阅“文本”控件
    txtText=(EditText)findViewById(R.id.txtText);
    //处理按钮“Speak”的onClick事件
    btnSpeak.setOnClickListener(新视图.OnClickListener(){
    公共void onClick(视图arg0){
    //方法尚未定义
    说话();
    }
    });
    }
    私人空谈{
    //把文本打出来
    字符串text=txtText.getText().toString();
    //如果未键入文本,tts将读取“您未键入文本”
    //否则它会读出你键入的文本
    如果(text.length()==0){
    tts.speak(“您尚未键入文本”,TextToSpeech.QUEUE\u FLUSH,null);
    }否则{
    tts.speak(text,TextToSpeech.QUEUE\u FLUSH,null);
    }
    }
    公共空间{
    //别忘了关机!
    如果(tts!=null){
    tts.stop();
    tts.shutdown();
    }
    super.ondestory();
    }
    @凌驾
    公共布尔onCreateOptions菜单(菜单){
    //为菜单充气;这会将项目添加到操作栏(如果存在)。
    getMenuInflater().充气(R.menu.texttovoice,menu);
    返回true;
    }
    @凌驾
    公共布尔值onOptionsItemSelected(菜单项项){
    //处理操作栏项目单击此处。操作栏将
    //自动处理Home/Up按钮上的点击,只要
    //在AndroidManifest.xml中指定父活动时。
    int id=item.getItemId();
    if(id==R.id.action\u设置){
    返回true;
    }
    返回super.onOptionsItemSelected(项目);
    }
    公共无效onInit(int状态){
    //TODO自动生成的方法存根
    //TTS已成功初始化
    if(status==TextToSpeech.SUCCESS){
    //设置语音语言
    int result=tts.setLanguage(Locale.US);
    //如果您的设备不支持上面设置的语言
    if(result==TextToSpeech.LANG_缺少_数据
    ||结果==TextToSpeech.LANG(不支持){
    //烹饪简单的祝酒词和祝酒词
    Toast.makeText(getApplicationContext(),“不支持语言”,
    Toast.LENGTH_LONG).show();
    Log.e(“TTS”,“不支持语言”);
    }
    //启用按钮-它在main.xml中被禁用(返回并
    //(检查一下)
    否则{
    btnSpeak.setEnabled(真);
    }
    //TTS未正确初始化
    }否则{
    Toast.makeText(此“TTS初始化失败”,Toast.LENGTH\u LONG)
    .show();
    Log.e(“TTS”,“初始化失败”);
    }
    }
    //-------------------------------XML---------------
    
    试试这个,很简单: **speakout.xml:**

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3498db"
    android:weightSum="1"
    android:orientation="vertical" >
    <TextView
    android:id="@+id/txtheader"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    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_width="match_parent"
    android:layout_weight=".5"
    android:background="#fff"
    android:textColor="#2c3e50"
    android:text="Hi there!!!"
    android:padding="5dp"
    android:gravity="top|left"
    android:layout_height="0dp"/>
    <Button
    android:id="@+id/btnspeakout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".1"
    android:background="#e74c3c"
    android:textColor="#fff"
    android:text="SPEAK OUT"/>
    </LinearLayout>
    
    来源

    package com.keshav.speechtotexample;
    导入java.util.ArrayList;
    导入java.util.Locale;
    导入android.app.Activity;
    导入android.content.ActivityNotFoundException;
    导入android.content.Intent;
    导入android.os.Bundle;
    导入android.speech.RecognizerIntent;
    导入android.view.Menu;
    导入android.view.view;
    导入android.widget.ImageButton;
    导入android.widget.TextView;
    导入android.widget.Toast;
    公共类MainActivity扩展了活动{
    私有文本视图txtSpeechInput;
    专用图像按钮btnSpeak;
    专用最终输入要求代码语音输入=100;
    @凌驾
    创建时受保护的void(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtSpeechInput=(TextView)findViewById(R.id.txtSpeechInput);
    btnSpeak=(图像按钮)findViewById(R.id.btnSpeak);
    //隐藏操作栏
    getActionBar().hide();
    btnSpeak.setOnClickListener(新视图.OnClickListener(){
    @凌驾
    公共void onClick(视图v){
    promptSpeechInput();
    }
    });
    }
    /**
    *显示谷歌语音输入对话框
    * */
    私有无效promptSpeechInput(){
    意向意向=新意向(识别意向、行动、识别言语);
    intent.putExtra(识别器intent.EXTRA_语言_模型,
    识别者意图、语言、模型、自由形式);
    intent.putExtra(RecognizerIntent.EXTRA_语言,Locale.getDefault());
    intent.putExtra(识别器intent.EXTRA\u提示符,
    getString(R.string.speech_提示符);
    试一试{
    startActivityForResult(意图、请求代码、语音输入);
    }捕获(ActivityNotFoundException a){
    Toast.makeText(getApplicationContext(),
    getString(R.string.speech\u编号
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3498db"
    android:weightSum="1"
    android:orientation="vertical" >
    <TextView
    android:id="@+id/txtheader"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    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_width="match_parent"
    android:layout_weight=".5"
    android:background="#fff"
    android:textColor="#2c3e50"
    android:text="Hi there!!!"
    android:padding="5dp"
    android:gravity="top|left"
    android:layout_height="0dp"/>
    <Button
    android:id="@+id/btnspeakout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".1"
    android:background="#e74c3c"
    android:textColor="#fff"
    android:text="SPEAK OUT"/>
    </LinearLayout>
    
    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
        }
    }
    
    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_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg_gradient"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/txtSpeechInput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            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_width="wrap_content"
            android:layout_height="wrap_content"
            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_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@null"
                android:src="@drawable/ico_mic" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                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>
    
    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);
                }
            }
       });
    }
    
        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;
                }
    }