วิธีหนึ่งในการสื่อสารกับผู้ใช้คือการใช้การอ่านออกเสียงข้อความ (TTS) TTS ในตัวของ Android ไม่ต้องใช้ไลบรารีเพิ่มเติมและทำงานแบบออฟไลน์ได้ ลักษณะเหล่านี้ทำให้ TTS เหมาะอย่างยิ่งสำหรับการจัดการสภาวะข้อผิดพลาดในแว่นตาเสียงหรือเมื่อจอแสดงผลปิดอยู่ คุณสามารถใช้ฟีเจอร์ TTS ผ่านคลาส TextToSpeech ได้
สร้างอินสแตนซ์ TextToSpeech
TextToSpeech จะเริ่มต้นแบบอะซิงโครนัส สร้างอินสแตนซ์ในเมธอด onCreate ของกิจกรรมที่คาดการณ์ไว้ รอ TextToSpeech.SUCCESS ใน OnInitListener และกำหนดค่าคำพูด AudioAttributes ก่อนพูด หาก onStart ทำงานก่อนที่การเริ่มต้นจะเสร็จสิ้น ให้จัดคิวคำทักทายและพูดภายใน Listener แทนที่จะทิ้งคำพูดนั้นไป
private var tts: TextToSpeech? = null
private var isTtsReady = false
private var pendingUtterance: Pair<String, String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
tts = TextToSpeech(this) { status ->
if (status == TextToSpeech.SUCCESS) {
tts?.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
)
isTtsReady = true
pendingUtterance?.let { (text, utteranceId) ->
pendingUtterance = null
speakWhenReady(text, utteranceId)
}
}
}
}
แจ้งเตือนผู้ใช้เมื่อ TTS เริ่มทำงาน
สำหรับแว่นตาที่มีระบบเสียง (และแว่นตาที่มีจอแสดงผลเมื่อจอแสดงผลปิดอยู่) ให้ยืนยันการเปิดใช้งานทันทีใน onStart โดยเล่นเอียร์คอน app_open.ogg ทั่วไปพร้อม SoundPool ขณะรอให้เครื่องมือ TTS เริ่มต้นทำงาน จากนั้นพูดข้อความเปิดดังนี้
override fun onStart() {
super.onStart()
// Preloaded with SoundPool; see the Gemini Live guide for a helper example.
earconPlayer.playAppOpen()
speakWhenReady("Welcome to Android XR glasses.", "welcome_utterance")
}
private fun speakWhenReady(text: String, utteranceId: String) {
if (!isTtsReady) {
pendingUtterance = text to utteranceId
return
}
tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId)
}
ประเด็นสำคัญเกี่ยวกับโค้ด
- การติดตาม
isTtsReadyและpendingUtteranceจะช่วยหลีกเลี่ยงการทิ้งคำพูดหากonStartทำงานก่อนที่เครื่องมือTextToSpeechจะเริ่มต้นเสร็จสิ้น TextToSpeech.QUEUE_FLUSHระบุว่าควรพูดข้อความทันทีและควรขัดจังหวะคำพูดก่อนหน้าในคิวutteranceId(ในกรณีนี้คือ"welcome_utterance") จะระบุเวลาที่ TTS พูดคำนั้นจบ โปรดดูรายละเอียดที่หัวข้อUtteranceProgressListener
ขัดจังหวะ TTS
หากแอปของคุณจำเป็นต้องขัดจังหวะ TTS เช่น ก่อนที่ Gemini Live จะเริ่มเล่นเสียงของโมเดลเพื่อไม่ให้เสียง 2 เสียงทับซ้อนกัน ให้เรียกใช้เมธอด stop ดังนี้
// Interrupts the current utterance and discards queued utterances.
tts?.stop()
ล้างทรัพยากร TTS
ล้างทรัพยากรเมื่อกิจกรรมถูกทำลายโดยการเรียกใช้ shutdown ภายในเมธอด onDestroy ของกิจกรรม
override fun onDestroy() {
super.onDestroy()
tts?.shutdown()
}