Android使用文本转语音播报

添加权限:


一:界面布局




    
        

        

二:调用

package com.example.texttospeech;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;

public class MainActivity extends AppCompatActivity{
    private EditText editText;
    private Button button;
    private TextToSpeech toSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initTextToSpeech();

        initView();
    }

    private void initView() {
        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(editText.getText().toString().trim())) {
                    play();
                } else {
                    Toast.makeText(MainActivity.this, "要转化为语音的文本不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 初始化语音
    private void initTextToSpeech() {
        toSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    // 设置首选项为中文
                    int result =toSpeech.setLanguage(Locale.CHINA);
                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
                        Toast.makeText(MainActivity.this, "语言数据丢失或不支持中文", Toast.LENGTH_SHORT).show();
                    }
                    play();
                }
            }
        });
        // 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
        toSpeech.setPitch(1.5f);
        // 设置语速
        toSpeech.setSpeechRate(1.0f);
    }

    // 播放语音
    private void play(){
        if (toSpeech != null && !toSpeech.isSpeaking()) {
            toSpeech.speak(editText.getText().toString().trim(), TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 页面可见,自动播放语音
        play();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 页面不可见,不管是否正在播放语音都被打断
        toSpeech.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 页面销毁,停止语音,释放资源
        if(toSpeech != null) {
            toSpeech.stop();
            toSpeech.shutdown();
        }
    }
}

你可能感兴趣的:(android,android,studio)