使用辅助功能流时TextToSpeech崩溃

时间:2019-03-27 15:23:23

标签: java android text-to-speech

您好,我正在尝试通过API 26中添加的辅助功能流使TextToSpeech正常工作。 我尝试使用docs中所述的bundle参数,但是代码使TTS引擎崩溃。

代码如下:

Bundle mParamsBundle = new Bundle();
if (Build.VERSION.SDK_INT >= 26) {
        mParamsBundle.putString(TextToSpeech.Engine.KEY_PARAM_STREAM,
                String.valueOf(AudioManager.STREAM_ACCESSIBILITY));
}

mTextToSpeech.speak(sentence,
                modeAddToQueue ? TextToSpeech.QUEUE_ADD : TextToSpeech.QUEUE_FLUSH,
                mParamsBundle, null);

TTS总是崩溃,此日志显示:

I/TextToSpeech: Asked to disconnect from ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}

I/TextToSpeech: Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}

I/TextToSpeech: Set up connection to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}

我在这里做错了什么?帮助将不胜感激

完整代码:

import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;

import java.util.Locale;

public class TextToSpeechHelper implements TextToSpeech.OnInitListener {

    final private static float SPEECH_RATE = 0.9f;
    private TextToSpeech mTextToSpeech;
    private Bundle mParamsBundle;
    private Locale mLocale;

    public TextToSpeechHelper(Context context, Locale locale) {
        mTextToSpeech = new TextToSpeech(context, this);
        mLocale = locale;
        mParamsBundle = new Bundle();

        if (Build.VERSION.SDK_INT >= 26) {
            mParamsBundle.putString(TextToSpeech.Engine.KEY_PARAM_STREAM,
                    String.valueOf(AudioManager.STREAM_ACCESSIBILITY));
        }
    }

    public void speak(String sentence) {
        speak(sentence, true);
    }

    public void speak(String sentence, boolean modeAddToQueue) {
        if (Build.VERSION.SDK_INT >= 21) {
            mTextToSpeech.speak(sentence,
                    modeAddToQueue ? TextToSpeech.QUEUE_ADD : TextToSpeech.QUEUE_FLUSH,
                    mParamsBundle, null);
        } else {
            mTextToSpeech.speak(sentence,
                    modeAddToQueue ? TextToSpeech.QUEUE_ADD : TextToSpeech.QUEUE_FLUSH,null);
        }
    }

    public boolean isSpeaking() {
        return mTextToSpeech.isSpeaking();
    }

    public void release() {
        mTextToSpeech.shutdown();
    }

    @Override
    public void onInit(int status) {
        if(status != TextToSpeech.ERROR) {
            mTextToSpeech.setLanguage(mLocale);
            //mTextToSpeech.setSpeechRate(SPEECH_RATE);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

根据此https://android.googlesource.com/platform/frameworks/base/+/master/media/java/android/media/PlayerBase.java#614,除了使用音量控制外,似乎不应使用STREAM_ACCESSIBILITY