我正在编写一个Android应用程序,从文件夹中获取最新的电子邮件,并使用TTS播放它。我希望能够使用它,同时驾驶,所以它必须主要是自动的。到目前为止,一切都很好,直到我尝试捕捉到TextToSpeech何时已经发言,以便我们可以继续下一封电子邮件。
以下是完整的MainActivity.java文件:
package uk.co.letsdelight.emailreader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
public TextToSpeech tts;
private Bundle ttsParam = new Bundle();
public UtteranceProgressListener utListener;
private boolean isPlaying = false;
private Properties imap = new Properties();
private String textToSpeak = "";
@Override
public void onInit(int ttsStatus) {
if (ttsStatus == TextToSpeech.SUCCESS) {
utListener = new UtteranceProgressListener() {
@Override
public void onStart(String s) {
TextView status = findViewById(R.id.status);
status.setText("started reading (Listener)");
}
@Override
public void onDone(String s) {
Toast.makeText(getApplicationContext(), "Done Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("finished reading (Listener)");
/*ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);*/
isPlaying = false;
}
@Override
public void onStop(String s, boolean b) {
Toast.makeText(getApplicationContext(), "Stop Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("stopped reading (Listener)");
/*ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);*/
isPlaying = false;
}
@Override
public void onError(String s) {
Toast.makeText(getApplicationContext(), "Error Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("Error reading email");
ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);
isPlaying = false;
}
};
tts.setOnUtteranceProgressListener(utListener);
TextView status = findViewById(R.id.status);
status.setText("initialised");
} else {
TextView status = findViewById(R.id.status);
status.setText("failed to initialise");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imap.setProperty("mail.store.protocol", "imap");
imap.setProperty("mail.imaps.port", "143");
tts = new TextToSpeech(this,this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void restartPressed(View v) {
if (isPlaying) {
tts.stop();
speak();
}
}
public void playPressed(View v) {
ImageButton i = (ImageButton) v;
if (isPlaying) {
isPlaying = false;
i.setImageResource(R.drawable.button_play);
TextView status = findViewById(R.id.status);
status.setText("");
if (tts != null) {
tts.stop();
}
} else {
isPlaying = true;
i.setImageResource(R.drawable.button_stop);
new Reader().execute();
}
}
class Reader extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
TextView status = findViewById(R.id.status);
status.setText("fetching email");
}
@Override
protected String doInBackground(String... params) {
String toRead = "nothing to fetch";
try {
Session session = Session.getDefaultInstance(imap, null);
Store store = session.getStore();
store.connect(getText(R.string.hostname).toString(), getText(R.string.username).toString(), getText(R.string.password).toString());
Folder inbox = store.getFolder("INBOX.Articles.listen");
if (inbox.exists() && inbox.getMessageCount() > 0) {
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount() - 6);
if (msg.getContentType().contains("multipart")) {
Multipart multiPart = (Multipart) msg.getContent();
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(multiPart.getCount() - 1);
toRead = part.getContent().toString();
} else {
toRead = msg.getContent().toString();
}
} else {
toRead = "The folder is empty or doesn't exist";
}
} catch (Throwable ex) {
toRead = "Error fetching email - " + ex.toString();
}
return toRead;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String body;
TextView status = findViewById(R.id.status);
status.setText("");
try {
Document doc = Jsoup.parse(s);
body = doc.body().text();
} catch (Throwable ex) {
body = "Error parsing email - " + ex.toString();
}
status.setText("email successfully fetched");
textToSpeak = body;
if (isPlaying) {
speak();
}
}
}
private void speak() {
int maxLength = TextToSpeech.getMaxSpeechInputLength();
if (textToSpeak.length() > maxLength) {
textToSpeak = "The email text is too long! The maximum length is " + maxLength + " characters";
}
ttsParam.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "EmailReader");
tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, ttsParam, "EmailReader");
}
@Override
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}内部类Reader运行良好。doInBackground获取电子邮件,onPostExec删除任何HTML以保留电子邮件的实际文本内容。这将传递给speak()方法,该方法执行实际的操作和工作。
问题在于onUtteranceProgressListener。
有时调用onStart(String s)方法,有时不是!第一次读电子邮件时,似乎从来没有人打过电话。大多数情况下,它是对speak()的后续调用,但并不总是这样。大约每5次就有1次没有被呼叫。如果被称为侦听器,则状态显示“已开始读取(侦听器)”,否则会显示“已成功获取电子邮件”。
onDone、onError和onStop从未被调用过。
我尝试在utteranceID调用中使用不同的Bundle和tts.speak()值,但这会产生不同的效果。
当应用程序启动时,第一个状态显示被“初始化”,这意味着onUtteranceListener必须是在onInit方法中设置的。TextToSpeech对象在活动的onCreate方法中实例化。
我已经翻阅了所有我能找到的信息,这些信息大多都表明了utteranceID是正确的。为了更好地理解这个问题,我还能做些什么呢?
发布于 2018-09-24 08:36:07
问题是onDone()方法(以及实际上任何进度回调)都是在后台线程上运行的,因此Toast无法工作,任何访问UI的代码(如setText(.)可能成功也可能不起作用。
所以..。这些方法可能正在被调用,但您只是看不到。
解决这一问题的方法是用runOnUiThread()包围回调中的代码,如下所示:
@Override
public void onDone(String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Done Event Listener", Toast.LENGTH_LONG).show();
TextView status = findViewById(R.id.status);
status.setText("finished reading (Listener)");
/*ImageButton i = findViewById(R.id.playButton);
i.setImageResource(R.drawable.button_play);*/
isPlaying = false;
}
});
}注意:最好是在TextView ()和其他所有东西中初始化您的onCreate,而不是在进程回调中。
此外,utteranceID的目的是给每个调用Also ()一个唯一的标识符,然后作为进度回调中的"String“参数传递给您。
让每个调用使用某种随机数生成器来发出一个新的(“最近的”) ID,然后在进程回调中检查它,这是一个好主意。
对于这个here,您可以看到类似的问题和答案。
附带说明:
因为您有一个“重新启动”按钮,所以您应该知道,在API <23上,对TextToSpeech.stop()的调用将导致调用进度侦听器中的onDone()。在API 23+上,它将调用onStop()。
发布于 2018-09-23 15:27:02
首先,确保您实际上有一个问题,而不是在谁设置文本的顺序之间的竞争。使用log语句确保不实际调用它。
尝试将queueMode设置为QUEUE_ADD,例如:
tts.speak(textToSpeak, TextToSpeech.QUEUE_ADD, ttsParam, "EmailReader");正如QUEUE_FLUSH建议的那样,可能后续的调用正在取消先前文本输入中的侦听器事件。
而且,这里并不真正需要这个包,您可以将它设置为null。
希望这些能帮上忙。
https://stackoverflow.com/questions/52465605
复制相似问题