Add support for JavaScript SpeechSynthesis API.

This commit is contained in:
Nolan Darilek 2019-12-31 08:54:13 -06:00
parent ecfee60db5
commit bf6372a1a8

34
TTS.gd
View File

@ -1,27 +1,35 @@
tool tool
extends Node extends Node
const TTS = preload("godot-tts.gdns") var TTS
var tts = null var tts = null
func _ready(): func _ready():
# Only initialize TTS if it's available or if we're in the editor. if not OS.has_feature('JavaScript') and not Engine.has_singleton("AndroidTTS"):
if TTS.can_instance() or Engine.editor_hint: TTS = preload("godot-tts.gdns")
print_debug("Attempting to load TTS.") if OS.has_feature('JavaScript'):
tts = TTS.new() pass
elif Engine.has_singleton("AndroidTTS"): elif Engine.has_singleton("AndroidTTS"):
tts = Engine.get_singleton("AndroidTTS") tts = Engine.get_singleton("AndroidTTS")
elif TTS.can_instance() or Engine.editor_hint:
tts = TTS.new()
else: else:
print_debug("TTS not available!") print_debug("TTS not available!")
var javascript_rate = 50
func set_rate(rate): func set_rate(rate):
if tts != null: if tts != null:
tts.rate = rate tts.rate = rate
elif OS.has_feature('JavaScript'):
javascript_rate = rate
func get_rate(): func get_rate():
if tts != null: if tts != null:
return tts.rate return tts.rate
elif OS.has_feature('JavaScript'):
return javascript_rate
else: else:
return 0 return 0
@ -31,14 +39,30 @@ func speak(text, interrupt := true):
print_debug("%s: %s" % [text, interrupt]) print_debug("%s: %s" % [text, interrupt])
if tts != null: if tts != null:
tts.speak(text, interrupt) tts.speak(text, interrupt)
elif OS.has_feature('JavaScript'):
var scaled_rate = javascript_rate / 2
var code = """
let utterance = new SpeechSynthesisUtterance("%s")
utterance.rate = %s
""" % [text, scaled_rate]
if interrupt:
code += """
window.speechSynthesis.cancel()
"""
code += "window.speechSynthesis.speak(utterance)"
JavaScript.eval(code)
func stop(): func stop():
if tts != null: if tts != null:
tts.stop() tts.stop()
elif OS.has_feature('JavaScript'):
JavaScript.eval("window.speechSynthesis.cancel()")
func get_is_rate_supported(): func get_is_rate_supported():
if Engine.get_singleton("AndroidTTS"): if Engine.get_singleton("AndroidTTS"):
return false return false
elif OS.has_feature('JavaScript'):
return true
elif tts != null: elif tts != null:
return tts.is_rate_supported() return tts.is_rate_supported()
else: else: