Android开发 使用TTS语音播放中英文

该方法为使用手机自带引擎,简单调用tts
手机需装有tts引擎,可参考下载该博主提供的数据。
https://blog.csdn.net/yingchengyou/article/details/79591954

1定义TTS

private TextToSpeech mtts;

2 播放方法

 private void playByTts(final Context context, final String text, final Locale locale) throws Exception {
    
    
        if (mtts!= null && mtts.isSpeaking() ) {
    
    
            return;
        }
        if (mtts== null) {
    
    
            mtts= new TextToSpeech(context, new TextToSpeech.OnInitListener() {
    
    
                @Override
                public void onInit(int status) {
    
    
                    if (status == TextToSpeech.SUCCESS) {
    
    
                        int result = mTts.setLanguage(locale);
                        if (result != TextToSpeech.LANG_MISSING_DATA &&
                                result != TextToSpeech.LANG_NOT_SUPPORTED) {
    
    
                            convertTextToSpeech(context, text);
                        }
                    }
                }
            });
        } else {
    
    
            convertTextToSpeech(context, text);
        }
    }

3 使用方法

手机自带pico引擎默认只有英文
playByTts(context, text, Locale.ENGLISH);
使用其他引擎,如科大讯飞,可播放中文
playByTts(context, text, Locale.SIMPLIFIED_CHINESE);

使用时根据具体要播放的内容,再更改/传入context和text即可。

猜你喜欢

转载自blog.csdn.net/weixin_52282455/article/details/141182886