-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
176 lines (144 loc) · 5.23 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
const enlacesCategorias = document.querySelectorAll("a");
enlacesCategorias.forEach((enlace) => {
enlace.addEventListener("click", function (event) {
event.preventDefault();
const categoriaSeleccionada = enlace.dataset.category;
// Almacenar la categoría seleccionada en localStorage
localStorage.setItem("categoriaSeleccionada", categoriaSeleccionada);
// Redirigir manualmente al enlace
window.location.href = enlace.href;
});
});
if (
window.location.pathname.endsWith("game.html") ||
window.location.pathname.endsWith("game")
) {
// Recuperar la categoría seleccionada desde localStorage
const categoriaSeleccionada = localStorage.getItem("categoriaSeleccionada");
let palabraSeleccionada = "";
if (categoriaSeleccionada) {
// Cargar las palabras desde el archivo JSON
fetch("words.json")
.then((response) => response.json())
.then((data) => {
const categoria = data.categories.find(
(cat) => cat.category === categoriaSeleccionada
);
if (categoria) {
const palabras = categoria.words;
seleccionarPalabraAleatoria(palabras);
} else {
console.error("Categoría no encontrada en el JSON.");
}
})
.catch((error) => console.error("Error al cargar las palabras:", error));
} else {
console.error("No se ha seleccionado ninguna categoría.");
}
// Seleccionar una palabra aleatoria y mostrarla
function seleccionarPalabraAleatoria(palabras) {
if (palabras.length > 0) {
const indiceAleatorio = Math.floor(Math.random() * palabras.length);
palabraSeleccionada = palabras[indiceAleatorio];
document.getElementById("word").textContent = palabraSeleccionada; // Mostrar la palabra en el HTML
} else {
console.error("No hay palabras disponibles para seleccionar.");
}
}
// Variables para la voz y la configuración de la pronunciación
let availableVoices = [];
let selectedVoice = null;
// Cargar voces disponibles
function cargarVoces() {
availableVoices = window.speechSynthesis.getVoices();
selectedVoice = availableVoices.find((voice) => voice.lang === "en-US");
}
window.speechSynthesis.onvoiceschanged = function () {
cargarVoces();
};
// Función para escuchar la pronunciación correcta
function reproducirPronunciacion() {
if (palabraSeleccionada) {
const synth = window.speechSynthesis;
// Detener cualquier reproducción en curso
synth.cancel();
const utterThis = new SpeechSynthesisUtterance(palabraSeleccionada);
utterThis.lang = "en-US"; // Configurar idioma inglés
// Asignar la voz seleccionada, si existe
if (selectedVoice) {
utterThis.voice = selectedVoice;
}
// Ajustar velocidad y tono
utterThis.rate = 0.9;
utterThis.pitch = 1.0;
synth.speak(utterThis);
} else {
console.error("No hay palabra seleccionada para pronunciar.");
}
}
//Función para escuchar la pronunciación del usuario
function iniciarReconocimiento() {
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
console.error(
"API de reconocimiento de voz no soportada en este navegador."
);
return;
}
activarBoton();
const recognition = new SpeechRecognition();
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.start();
recognition.onresult = function (event) {
const userAttempt = event.results[0][0].transcript;
const newUserAttempt = userAttempt.replace(/\./g, "");;
document.getElementById(
"userAttempt"
).textContent = `${newUserAttempt}`;
verificarPronunciacion(userAttempt);
};
recognition.onerror = function (event) {
console.error("Error en el reconocimiento:", event.error);
};
}
//Función para botón activo
const btnGrabar = document.getElementById("startRecognition");
function activarBoton() {
btnGrabar.textContent = "🎙️ Listening...";
btnGrabar.style.backgroundColor = "#f44336";
btnGrabar.disabled = true;
}
//Función para botón inactivo
function desactivarBoton() {
btnGrabar.textContent = "🎤 Start Recording";
btnGrabar.style.backgroundColor = "#4caf50";
btnGrabar.disabled = false;
}
//Función para verificar la pronunciación
function verificarPronunciacion(userAttempt) {
const mensajeResultado = document.getElementById("resultMessage");
const newUserAttempt = userAttempt.replace(/\./g, "");;
// Normalizar las cadenas para evitar errores de comparación
if (
newUserAttempt.trim().toLowerCase() ===
palabraSeleccionada.trim().toLowerCase()
) {
mensajeResultado.textContent = "¡Correcto!";
mensajeResultado.className = "success";
} else {
mensajeResultado.textContent = "Inténtalo de nuevo.";
mensajeResultado.className = "fail";
}
desactivarBoton();
}
// Eventos para los botones
document
.getElementById("playPronunciation")
.addEventListener("click", reproducirPronunciacion);
document
.getElementById("startRecognition")
.addEventListener("click", iniciarReconocimiento);
}