Android Studio开发安卓app TTS学习,使用TextToSpeech类完成输入文字播放中文

本文介绍了如何在Android Studio中使用TextToSpeech类进行文本转语音的功能开发,包括创建Empty Activity、配置支持API24以上系统、修改布局文件和Java代码,以及遇到的真机和模拟器测试问题,特别是解决TTS在后台失效的问题。

安卓TextToSpeech

Android允许您将文本转换为语音。您不仅可以转换它,还可以用多种不同的语言说文本。Android 为此提供了TextToSpeech类。为了使用此类,您需要实例化此类的对象并指定initListener。

创建 Empty Activity

我选择的API24,支持安卓7.0及以上的操作系统。

修改默认的 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity"
    android:transitionGroup="true">

    <TextView android:text="文字转语音示例"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textview"
        android:textSize="35sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />





    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"

        android:layout_marginTop="46dp"
        android:hint="输入文字"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="#ff7aff10"
        android:textColorHint="#ffff23d1" />

    <Button
        android:id="@+id/button"
        android:layout_width="130dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp"
        android:text="文字转语音" />

</RelativeLayout>

修改默认的MainActivity.java

package com.tianxuan.tts;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Locale;

/**
 *
 * AppCompatActivity和Activity的区别
 *
 * AppCompatActivity,是继承与Activity的,当然集成了很多代以前才是Activity
 *
 * 首先是AppCompatActivity默认带标题
 * 但Activity不带
 *
 * 而且AppCompatActivity和
 * requestWindowFeature(Window.FEATURE_NO_TITLE);
 * 有冲突,用了没效果
 *
 */
public class MainActivity extends Activity {
    TextToSpeech textToSpeech;
    EditText editText;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText=(EditText)findViewById(R.id.editText);
        button=(Button)findViewById(R.id.button);

        //初始哈TTS对象
        textToSpeech=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    //设置语言
                    textToSpeech.setLanguage(Locale.CHINA);
                }
            }
        });

        /**
         * 按钮点击事件 获取输入的文字 调用textToSpeech.speak播放语音
         */
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String toSpeak = editText.getText().toString();
                Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
                Log.d("setOnClickListener",toSpeak);
                textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
            }
        });
    }

    //onPause表示当前页面失去焦点。
    public void onPause(){
        if(textToSpeech !=null){
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onPause();
    }

}

真机测试

真机测试是可以的,把手机音量都打开,输入文字正常播放
在这里插入图片描述

模拟器运行测试

模拟器测试报错 W/TextToSpeech: speak failed: not bound to TTS engine
提示没安装TTS引擎,网上也有很多安卓TTS引擎下载,支持中文的也有,下载后是apk文件,直接安装后在系统设置–》无障碍–》TTS语音 里设置安装的TTS引擎即可

科大讯飞TTS引擎已上传,支持中文,亲测可用
https://download.csdn.net/download/qq445829096/85882774

在这里插入图片描述在这里插入图片描述

问题处理

TTS无效

项目上使用发现APP只要一切换到后台运行后TTS就失效,在切回来也没用,必须重新启动app

解决方案:改为每次new一个tts对象在呼叫。 JsInteration在封装一个textToSpeechPrototypeMode方法暴露给H5调用,当H5有后台运行的场景时可使用

/**
     * java方法  供H5调用 TTS 传入文字播放语言
     * 单例模式 TTS语音只初始化一次
     * @return
     */
    @JavascriptInterface
    public String textToSpeech(String text) {
        Log.d("textToSpeech",text);
        textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        return "textToSpeech success";
    }


    /**
     * java方法  供H5调用 TTS 传入文字播放语言
     * PrototypeMode 原型模式  每次都new一个tts对象
     * 用途:单例模式只初始化一次,切换到后台运行就 TTS就不能用了, 有些场景需要频繁切换app到后台
     * 或者app就是在在后台运行专门提供TTS叫号服务  需要用到 PrototypeMode 原型模式
     * 每次new一个new TextToSpeech 不知道是否会有内存溢出问题
     * @return
     */
    @JavascriptInterface
    public String textToSpeechPrototypeMode(String text) {
        Log.d("textToSpeechPrototypeMode",text);



      textToSpeech  =new TextToSpeech( this.mContext, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    textToSpeech.setLanguage(Locale.CHINA);
                    textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);


                }
            }
        });

        return "textToSpeechPrototypeMode success";

    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值