安卓文字转语音

标签 android android-studio android-activity android-speech-api

我正在尝试使用 TextToSpeech 类在我的应用程序中说出文本。当我运行我的代码时,我没有听到任何声音,音量很高。我的代码有什么问题?我需要许可还是什么?

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener  {

    TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textToSpeech = new TextToSpeech(this, this);

        speakOut();
    }

    @Override
    public void onInit(int Text2SpeechCurrentStatus) {

        if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {

            int result = textToSpeech.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            } else {
                speakOut();
            }

        } else {
            Log.e("TTS", "Initilization Failed!");
        }
    }

    private void speakOut() {
        String g= "Hello";
        textToSpeech.speak(g, TextToSpeech.QUEUE_FLUSH, null);
    }
}

最佳答案

首先也是最重要的事情:检查您的设备中是否安装了任何 TTS 引擎。

不,您不需要任何许可即可使用 TTS。

像这样在 Activity 的 onCreate() 方法中初始化 TextToSpeech 实例。

TextToSpeech t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
     @Override
     public void onInit(int status) {
        if(status != TextToSpeech.ERROR) {
           t1.setLanguage(Locale.UK);
        }
     }
  });

//这是您的speakOut() 方法。

   private void speakOut() {
    String g= "Hello";
     t1.speak(g, TextToSpeech.QUEUE_FLUSH, null);
}

希望对你有帮助

关于安卓文字转语音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40879552/

相关文章:

Android - 将 XML 解析为 ArrayList

android - 如何从 firebase 数据库中检索包含子名称的字符串列表?

android-studio - Android NDK,错误 :(165, 0) 原因:找不到 ndk-build 二进制文件

android - 如何使 Activity 的背景半透明?

java - 使用堆栈 - 覆盖 onBackPressed

java - 如何找到特定的 Java 类定义?

android - Espresso : test startActivityForResult return RESULT_OK

android - 在 Android 上使用像素缓冲对象 (PBO)

android - 每次应用程序启动时都会创建 GCM 注册 ID?

android-studio - 安卓工作室 : Project Structure unavailable using Gradle KTS Build Files