Android通过TextToSpeech实现文字转语音 您所在的位置:网站首页 widget发音 Android通过TextToSpeech实现文字转语音

Android通过TextToSpeech实现文字转语音

2023-06-03 21:26| 来源: 网络整理| 查看: 265

一、直接上代码: 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; public class MainActivity extends Activity implements TextToSpeech.OnInitListener { TextToSpeech textToSpeech; EditText ed1; Button b1; String toSpeak; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1 = findViewById(R.id.editText); b1 = findViewById(R.id.button); textToSpeech = new TextToSpeech(getApplicationContext(), this); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toSpeak = ed1.getText().toString(); Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show(); // textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_ADD, null, null); } }); } public void onPause() { if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } super.onPause(); } @Override public void onInit(int status) { //判断是否转化成功 if (status == TextToSpeech.SUCCESS) { //设置语言为中文 int languageCode = textToSpeech.setLanguage(Locale.CHINA); //判断是否支持这种语言,Android原生不支持中文,使用科大讯飞的tts引擎就可以了 if (languageCode == TextToSpeech.LANG_NOT_SUPPORTED) { Log.d("TAG", "onInit: 不支持这种语言"); } else { //不支持就改成英文 textToSpeech.setLanguage(Locale.US); } //设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规 textToSpeech.setPitch(1.0f); //设置语速 textToSpeech.setSpeechRate(1.0f); //在onInIt方法里直接调用tts的播报功能 // textToSpeech.speak("李佩伦打卡成功", TextToSpeech.QUEUE_ADD, null); } } } 二、效果:输入‘中文’点击按钮发音

 三、Android高版本兼容

        如果在Android11里转语音不发声,并且报错:speak failed:not bound to TTS engine,则需要在AndroidManifest.xml文件中声明如下内容:

四、扩展

1、setLanguage支持的一些语言环境:

语言常量美式英语US加拿大法语CANADA_FRENCH德语GERMANY意大利语ITALY日语JAPAN汉语CHINA

 2、TextToSpeech类中的一些其他方法:

方法说明addSpeech(String text, String filename)此方法在文本字符串和声音文件之间添加映射。getLanguage()此方法返回描述语言的Locale实例。isSpeaking()此方法检查TextToSpeech引擎是否正在忙于讲话。setPitch(float pitch)此方法设置TextToSpeech引擎的语音音调。setSpeechRate(float speechRate)此方法设置语音速率。shutdown()此方法释放TextToSpeech引擎使用的资源。stop()这种方法停止说话。

3、播放的声音可在手机:设置->语言与输入法->文字转语音(TTS)输出 中进行设置,或安装其他平台语音识别模块并在此配置。

应用名称支持离线备注下载地址ITRI TTS是无下载讯飞语记是需打开一次, 但不需要登陆下载科大讯飞语音引擎3.0是推荐下载Speech Services by Google否需要科学上网, 离线需要先下载语音包下载


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有