在Android中,要實現(xiàn)TextToSpeech的暫停功能,你需要使用TextToSpeech
類的pause()
方法。以下是一個簡單的示例:
<uses-permission android:name="android.permission.INTERNET" />
TextToSpeech
對象,并實現(xiàn)暫停功能:import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements OnInitListener {
private TextToSpeech mTts;
private boolean isSpeaking = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化TextToSpeech對象
mTts = new TextToSpeech(this, this);
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(this, "TextToSpeech初始化成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "TextToSpeech初始化失敗", Toast.LENGTH_SHORT).show();
}
}
public void speak(String text) {
if (!isSpeaking) {
mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
isSpeaking = true;
}
}
public void pauseSpeaking() {
if (isSpeaking) {
mTts.pause();
isSpeaking = false;
}
}
}
在這個示例中,我們創(chuàng)建了一個TextToSpeech
對象,并在onInit()
方法中檢查其初始化狀態(tài)。我們還定義了兩個方法:speak()
用于開始說話,pauseSpeaking()
用于暫停說話。當調(diào)用pauseSpeaking()
方法時,TextToSpeech
對象的pause()
方法將被調(diào)用,從而實現(xiàn)暫停功能。