Android离线文字转语音(TTS)原生实现

目前文字转语音用的最多的是第三方厂商科大讯飞,不过需要收费。google也有离线文字转语音sdk,支持中文,发音也很好,使用免费的它不更香么!下边介绍具体使用步骤:

一、下载并设置Google文字转语音引擎

首先下载Google文字转语音引擎并安装。安装完成后在设置–>辅助功能–>无障碍–>文字转语音输出中将Google 文字转语音引擎设置为默认语音引擎。点击Google语音引擎设置,在引擎设置页面联网安装所需要的语音数据包。

下图为引擎设置页面:

Android离线文字转语音(TTS)原生实现_第1张图片

下图为引擎语音数据下载页面:

Android离线文字转语音(TTS)原生实现_第2张图片

下图为google语音引擎应用详情页面

Android离线文字转语音(TTS)原生实现_第3张图片

二、文字转语音编码实现

代码比较简单,就不讲解了,有需要的直接粘贴使用吧。

activity_main.xml




    

    

MainActivity.java

package com.furong.googletts;

import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Locale;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
    private TextView speechText;
    private TextToSpeech tts;
    private HashMap params;
    private String mostRecentUtteranceID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        speechText = findViewById(R.id.content_text);

        //Initialize TTS
        tts = new TextToSpeech(this, this);

        //Change the tone and speed to change the sound effect
        tts.setPitch(0.9f);
        tts.setSpeechRate(1.0f);

        //Set unique utterance ID for each utterance
        mostRecentUtteranceID = (new Random().nextInt() % 9999999) + "";

        //Set params
        //This method will work for more devices: API 19+
        params = new HashMap<>();
        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mostRecentUtteranceID);
    }

    public void startSpeak(View view) {
        if (tts != null && !tts.isSpeaking()) {
         int code = tts.speak(speechText.getText().toString(), TextToSpeech.QUEUE_FLUSH, params);
         if (code != SUCCESS) {
       			//do something
         	}
        }
    }

    @Override
    public void onInit(int status) {
        //Is TTS initialized successfully
        if (status == TextToSpeech.SUCCESS) {
            if (tts.getEngines().size() <= 0) {
                Toast.makeText(MainActivity.this, "Please install the voice engine", Toast.LENGTH_SHORT).show();
                return;
            }

            //The default language is Chinese
            int result = tts.setLanguage(Locale.CHINESE);
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Toast.makeText(MainActivity.this, "Chinese is not supported", Toast.LENGTH_SHORT).show();
                //Set to English when Chinese is not supported
                tts.setLanguage(Locale.US);
            }

            //Set voice to text progress monitoring
            tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                @Override
                public void onStart(String utteranceId) {
                }

                @Override
                public void onDone(String utteranceId) {
                    // only respond to the most recent utterance
                    if (!utteranceId.equals(mostRecentUtteranceID)) {
                        Log.i("MainActivity", "onDone() blocked: utterance ID mismatch.");
                        return;
                    }

                    boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
                    Log.i("MainActivity", "was onDone() called on a background thread? : " + wasCalledFromBackgroundThread);

                    // for demonstration only... avoid references to
                    // MainActivity (unless you use a WeakReference)
                    // inside the onDone() method, as it
                    // can cause a memory leak.
                    runOnUiThread(() -> {
                        //toast will not work if called from a background thread
                        Toast.makeText(MainActivity.this, "onDone working.", Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onError(String utteranceId) {
                }
            });
        }
    }
}

其他:

选择语音引擎时也可以在无障碍中选一个手机自带的支持中文的语音引擎(非必须 google引擎),在选择引擎后先使用手机自带的引擎发音测试测试下是否可以正常中文发音,测试成功后使用以上代码即可进行文字转语音播报的开发。

google语音引擎链接: https://pan.baidu.com/s/1J8HLhPfzKc8M73omHnIdMw 提取码: mm25

在使用语音引擎过程中有什么问题欢迎留言咨询~

你可能感兴趣的:(Android,文字转语音,TTS,Android文字转语音)