TTs技术 Text to speech

来源:互联网 发布:两个皇冠的淘宝店 编辑:程序博客网 时间:2024/05/17 01:00

    Android 1.6 开始支持TTS技术,(Text To Speach),通过该技术我们可以把文本转成语音。TTS的核心技术是 android.speech 类。要想使用TTS技术朗读文本,需要做两个工作———初始化TTS(指定TTS朗读文本的语言)和指定好要朗读的文本(通过speak方法指定朗读文本);

关键方法:

                    TextToSpeech.OnInitListener.onInit初始化TTS

                     TextToSpeech.speak 方法来将文本转成语音

附上小demo

activity_main

<?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_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.shilixia.learntts.MainActivity">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/tv_showText"        android:text="@string/Text"        />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/btnChangetoSpeech"        android:text="转化"/></LinearLayout>
MainActivity.java

package com.shilixia.learntts;import android.speech.tts.TextToSpeech;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import java.util.Locale;public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener, View.OnClickListener {    private TextToSpeech TTS;    private TextView tv_ShowText;    private Button btnChangeToSpeech;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv_ShowText = (TextView) findViewById(R.id.tv_showText);        btnChangeToSpeech = (Button) findViewById(R.id.btnChangetoSpeech);        btnChangeToSpeech.setOnClickListener(this);        TTS = new TextToSpeech(this,this);    }    @Override    public void onInit(int status) {        if (status == TextToSpeech.SUCCESS){            int result = TTS.setLanguage(Locale.US);            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){                Toast.makeText(this,"有问题",Toast.LENGTH_LONG).show();            }        }    }    @Override    public void onClick(View v) {        TTS.speak(tv_ShowText.getText().toString(),TextToSpeech.QUEUE_FLUSH,null);    }}


       

0 0
原创粉丝点击