godot-tts/TTS.gd

83 lines
2.0 KiB
GDScript3
Raw Normal View History

tool
2019-09-24 19:21:05 +00:00
extends Node
var TTS
2020-01-15 01:54:40 +00:00
var tts
func _ready():
if OS.get_name() == "Server" or OS.has_feature("JavaScript"):
2020-01-09 21:54:05 +00:00
return
2019-12-30 18:57:19 +00:00
elif Engine.has_singleton("AndroidTTS"):
tts = Engine.get_singleton("AndroidTTS")
2020-01-10 14:49:43 +00:00
else:
TTS = preload("godot-tts.gdns")
if TTS and (TTS.can_instance() or Engine.editor_hint):
tts = TTS.new()
else:
print_debug("TTS not available!")
var javascript_rate = 50
2019-09-27 18:07:35 +00:00
func set_rate(rate):
if tts != null:
tts.rate = rate
elif OS.has_feature('JavaScript'):
javascript_rate = rate
2019-09-27 18:07:35 +00:00
func get_rate():
if tts != null:
return tts.rate
elif OS.has_feature('JavaScript'):
return javascript_rate
else:
return 0
2019-09-27 18:07:35 +00:00
var rate setget set_rate, get_rate
func speak(text, interrupt := true):
print_debug("%s: %s" % [text, interrupt])
if tts != null:
tts.speak(text, interrupt)
elif OS.has_feature('JavaScript'):
2019-12-31 18:26:26 +00:00
var scaled_rate = javascript_rate / 25
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():
if tts != null:
tts.stop()
elif OS.has_feature('JavaScript'):
JavaScript.eval("window.speechSynthesis.cancel()")
func get_is_rate_supported():
2019-12-30 18:57:19 +00:00
if Engine.get_singleton("AndroidTTS"):
return false
elif OS.has_feature('JavaScript'):
return true
2019-12-30 18:57:19 +00:00
elif tts != null:
return tts.is_rate_supported()
else:
return false
var is_rate_supported setget , get_is_rate_supported
func singular_or_plural(count, singular, plural):
if count == 1:
return singular
else:
return plural
2019-12-23 00:09:40 +00:00
func _exit_tree():
2020-01-09 21:54:05 +00:00
if not tts or not TTS:
return
2020-01-15 01:54:40 +00:00
tts.free()