【问题标题】:Text To Speech without textfield and button in Android StudioAndroid Studio中没有文本字段和按钮的文本到语音
【发布时间】:2019-05-06 04:01:47
【问题描述】:

所以,我想在 Android Studio 中不使用文本字段和按钮来创建文本转语音。例如,当我打开应用程序时,它会说“欢迎使用我的应用程序”,没有文本字段或任何按钮。我怎样才能做到这一点?需要你的帮助。

【问题讨论】:

  • 与其提供文本字段中的字符串,不如向它传递一个字符串,然后在 onViewCreated() 中调用文本转语音方法
  • 看看我对 TTS 服务的回答:stackoverflow.com/a/43262996/2597775

标签: java android text-to-speech


【解决方案1】:

你可以这样做:

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;

import java.util.Locale;

public class MainActivity extends Activity {

    TextToSpeech t1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t1.setLanguage(Locale.ENGLISH);
                }
            }
        });


        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                t1.speak("welcome to my app", TextToSpeech.QUEUE_FLUSH, null);
            }
        }, 100);


    }

    public void onPause() {
        if (t1 != null) {
            t1.stop();
            t1.shutdown();
        }
        super.onPause();
    }

}

代码是不言自明的,我对其进行了成功的测试。

【讨论】:

  • 我认为在 setLanguage 之后/使用 setLanguage 之后将 speak() 代码放在 onInit() 方法中会更好。您不能只假设引擎需要 100 毫秒来初始化。您不知道用户在他们的设备上使用了什么语音引擎,有时 Google 引擎需要长达 6000 毫秒的时间……所以您不妨等到它真正初始化后才说话。
【解决方案2】:

只需在你的 onCreate() 中添加这个:

myTTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    // replace this Locale with whatever you want                    
                    Locale localeToUse = new Locale("en","US");
                    myTTS.setLanguage(localeToUse);
                    myTTS.speak("Hi, Welcome to my app!", TextToSpeech.QUEUE_FLUSH, null);
                }
            }
        });

【讨论】:

  • 您好,先生。只是想问一下您给我的代码是否适用于 Android Studio?谢谢。
猜你喜欢
  • 2015-06-16
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多