gpt4 book ai didi

Android TTS onUtteranceCompleted 回调未被调用

转载 作者:可可西里 更新时间:2023-11-01 18:49:59 26 4
gpt4 key购买 nike

我试图让 Android TTS API 读取我的“话语”,然后调用 onUtteranceCompleted() 监听器失败。我已经注册了我的 TTS 对象,它返回了 SUCCESS,所以我终究无法弄清楚为什么我的回调没有被调用。

我曾尝试寻求帮助,但似乎其他人对此也有困难。我错过了一些简单的东西吗?

感谢您提供的任何帮助。

package com.test.mytts;

import java.util.HashMap;

import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.widget.TextView;
import android.widget.Toast;

public class MyTTS extends Activity implements OnInitListener, OnUtteranceCompletedListener
{
TextView tv;
private TextToSpeech _tts;

@Override
public void onCreate(Bundle savedInstanceState)
{
tv = new TextView(this);

tv.setText("MyTTS: ");

super.onCreate(savedInstanceState);
setContentView(tv);

_tts = new TextToSpeech(this, this);
}

@Override
public void onInit(int status)
{
HashMap<String, String> myHashAlarm = new HashMap<String, String>();

myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "test");

if (status == TextToSpeech.SUCCESS)
{
Toast.makeText(this, "Trying to speak...", Toast.LENGTH_SHORT).show();

int result = _tts.setOnUtteranceCompletedListener(this);

tv.append(String.valueOf(result));

_tts.setSpeechRate((float) .5);

_tts.speak("Testing one, two, three", TextToSpeech.QUEUE_ADD, myHashAlarm);
}
else
Toast.makeText(this, "Failed to initialize TTS.", Toast.LENGTH_SHORT).show();

}

@Override
public void onUtteranceCompleted(String utteranceId)
{
Toast.makeText(this, "onUtteranceCompleted", Toast.LENGTH_SHORT).show();
}

@Override
public void onDestroy()
{
super.onDestroy();
_tts.shutdown();
}
}

最佳答案

在 tts 对象的 onInit 函数中调用 setOnUtteranceCompletedListener。

如果您想在调用 onUtteranceCompleted 函数时对 UI 进行任何更改,请将代码添加到 runOnUIThread 方法中。

并且记得在调用 speak() 函数时添加 Hashmap 参数值

示例:

TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {

@Override
public void onInit(int status) {

mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {

@Override
public void onUtteranceCompleted(String utteranceId) {

runOnUiThread(new Runnable() {

@Override
public void run() {
//UI changes
}
});
}
});

}
});


HashMap<String, String> params = new HashMap<String, String>();

params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");

tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params);

关于Android TTS onUtteranceCompleted 回调未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4652969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com