{# nColNum must be passed as an argument to the twig include #}
<script>
{% set nAudioRate = app.session.get("current_audio_rate") %}
{% if not nAudioRate is null %}
MultiAudioElementTTS.globalRate = {{ nAudioRate }};
{% endif %}
const tts{{ nColNum }} = new MultiAudioElementTTS();
let stt{{ nColNum }} = null;
tts{{ nColNum }}.go = function() {
this.loadTextAndStartOrPause(
document.querySelector("#tts{{ nColNum }}").innerText,
"{{ app.session.get('user_id') }}"
);
}
tts{{ nColNum }}.next = function() {
const nextButton = document.querySelector("a.nav-arrow-next");
const url = URL.parse(nextButton.href);
url.searchParams.append("ttsautoplay", "{{ nColNum }}");
window.location = url;
}
tts{{ nColNum }}.onStateChange = function() {
if (this.isLoading){
$("#readbutton{{ nColNum }}").hide();
$("#loadingbutton{{ nColNum }}").show();
$("#stopbutton{{ nColNum }}").hide();
$("#pausebutton{{ nColNum }}").hide();
} else {
$("#loadingbutton{{ nColNum }}").hide();
if (this.hasStarted){
$("#stopbutton{{ nColNum }}").show();
if (this.canResume) {
$("#readbutton{{ nColNum }}").show();
$("#pausebutton{{ nColNum }}").hide();
} else {
$("#readbutton{{ nColNum }}").hide();
$("#pausebutton{{ nColNum }}").show();
}
} else {
$("#readbutton{{ nColNum }}").show();
$("#stopbutton{{ nColNum }}").hide();
$("#pausebutton{{ nColNum }}").hide();
}
}
}
tts{{ nColNum }}.onAllElementsEnded = function() {
const nextButton = document.querySelector("a.nav-arrow-next");
if (nextButton && nextButton.href) {
const endpoint = new URL("https://newchristianchatbot.org/api/tts/");
endpoint.searchParams.append("au", "{{ app.session.get('user_id') }}");
endpoint.searchParams.append("content", "{{ app.session.get('ui_str')['texttospeech.continueprompt']|raw }}");
const audio = document.createElement("audio");
audio.src = endpoint;
{# use setTimeout rather than `audio.addEventListener("ended", ...)` #}
{# to start listening for a response before the TTS finishes completely #}
setTimeout(() => {
if (stt{{ nColNum }} != null) {
stt{{ nColNum }}.start();
} else if (confirm("{{ app.session.get('ui_str')['texttospeech.continueprompt']|raw }}")) {
tts{{ nColNum }}.next();
}
}, 1500);
audio.play();
}
}
if (typeof SpeechRecognition !== "undefined" && typeof SpeechToText !== "undefined") {
stt{{ nColNum }} = new SpeechToText("{{ app.request.locale }}");
for (const phrase of ["{{ app.session.get('ui_str')['speechtotext.yes']|raw }}", "{{ app.session.get('ui_str')['speechtotext.okay']|raw }}"]) {
stt{{ nColNum }}.addPhrase(phrase, () => tts{{ nColNum }}.next());
}
}
{% if app.request.query.get("ttsautoplay") == nColNum~"" %}
addEventListener("DOMContentLoaded", () => tts{{ nColNum }}.go());
{% endif %}
</script>