Android文字转语音

时间:2016-11-30 03:06:02

标签: 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);
    }
}

2 个答案:

答案 0 :(得分:1)

首要的事情是:检查设备中是否装有任何TTS引擎。

不,你不需要任何使用TTS的许可。

在活动的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);
}

希望它有所帮助...

答案 1 :(得分:0)

这可能是评论,我不确定,但你可以试试 改变 if (Text2SpeechCurrentStatus == TextToSpeech.SUCCESS) {
进入 if (Text2SpeechCurrentStatus != TextToSpeech.ERROR) {

也许你可以调试,Text2SpeechCurrentStatus

的价值是多少