this may get closed as request for software, or opinion based but I'm hopeful it might not.
I wrote a JS web page for our church that uses speech recognition to transcribe the pastor's speech and display it as closed captions on a monitor. The accuracy is around 90%. I was wondering if anyone had suggestions to improve it or if using an API like Google Translate would help.
you can try it here. https://bryandellinger.github.io/voicetotext/
here it is in github
warning this version has a large list of profanities in it
https://github.com/bryandellinger/voicetotext/blob/main/index.html
below is the relevant code.
const badWords = ['apple', 'banana', 'orange', 'grape', 'pear']
window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition;
let finalTranscript = '';
let recognition = new window.SpeechRecognition();
recognition.interimResults = true;
recognition.maxAlternatives = 10;
recognition.continuous = true;
recognition.addEventListener('end', () => {
recognition.start();
});
recognition.onresult = (event) => {
let interimTranscript = '';
for (let i = event.resultIndex, len = event.results.length; i < len; i++) {
let transcript = (event.results[i][0].transcript);
const words = transcript.split(" ");
const words2 = [];
words.forEach(element => {
if (element.indexOf('*') < 0){
words2.push(element);
}
});
const filteredWords = words2.filter(word => !badWords.includes(word.toLowerCase()));
if (event.results[i].isFinal) {
finalTranscript += filteredWords.join(' ');
} else {
interimTranscript += filteredWords.join(' ');
}
}
interimTranscript = interimTranscript.length > 1000 ? interimTranscript.substring(1000) : interimTranscript;
finalTranscript = finalTranscript.length > 1000 ? finalTranscript.substring(1000) : finalTranscript;
document.querySelector('div').innerHTML = finalTranscript + '<i style="color:#FFFFFF;">' + interimTranscript + '</>';
const myDiv = document.getElementById('container');
myDiv.scrollTop = myDiv.scrollHeight;
}
recognition.start();
Related
I want to disable a submit button until all the inputs are filled using only JavaScript and am not using a form in HTML. Currently, the button is disabled but will not allow the user to submit once all the inputs are full. Does anyone know how to enable the submit button once the inputs are full?
JavaScript
document.addEventListener('DOMContentLoaded', function(){
const required = document.querySelectorAll('.input');
//gets all the quiz_buttons enableChecking();
const quizButton = document.querySelectorAll('.quiz_button');
for (const button of quizButton){
button.disabled = true;
for(let i = 0; i < required.length; i++){
required[i].addEventListener("input", () =>{
//what should I put here?
});
}
button.addEventListener('click', (event) => check_quiz(event.target.id));
}
});
function check_quiz(id){
console.log("button is clicked");
//get answers
let response1 = document.getElementById('id_question1').value.toUpperCase().replace(/\s/g, "");
//repeats 9 times
//get divs
let div1 = document.getElementById('div1');
//repeats 9 times
var correctAnswers = 0;
//get quiz
fetch(`/check/${id}`)
.then(response => response.json())
.then(quiz => {
let rightM = "You got this correct. Great job!";
//checking if the answers are right
//#1
let answ1 = quiz.answer1.toUpperCase().replace(/\s/g, "");
if(answ1 === response1){
div1.innerHTML = rightM;
div1.classList.add("correct");
correctAnswers++;
} else{
div1.innerHTML = `The correct answer is ${quiz.answer1}. Nice try!`;
div1.classList.add("incorrect");
}
//repeats 9 times
console.log(correctAnswers);
//display score
let score = document.getElementById("score");
score.innerHTML = `Your score is ${correctAnswers}. Great job! :)`;
score.classList.add("score_style");
//points
let newPoints = correctAnswers * 10;
let currentUser = parseInt(document.getElementById("user_id").value);
let currentPoints = parseInt(document.getElementById("user_points").value);
let numOfPoints = currentPoints + newPoints;
console.log(numOfPoints);
fetch(`/points/${currentUser}`,{
method: "PUT",
body: JSON.stringify({
points: numOfPoints
})
})
})
}
I omitted redundant parts of my code.
the simplest way is to check if every input has value when you type into input, try following code, this should work
document.addEventListener('DOMContentLoaded', function(){
const required = document.querySelectorAll('.input');
function checkSubmit(button) {
let isValid = true;
for(let i = 0; i < required.length; i++){
isValid = isValid && !!required[i].value;
}
button.disabled = isValid;
}
function inputHandler(button) {
return function () {
checkSubmit(button);
}
}
//gets all the quiz_buttons
const quizButton = document.querySelectorAll('.quiz_button');
for (const button of quizButton){
button.disabled = true;
for(let i = 0; i < required.length; i++){
required[i].addEventListener("input", inputHandler(button));
}
button.addEventListener('click', (event) =>
check_quiz(event.target.id));
}
});
I'm having problem with loading from local storage.
Here's a part of the code
const getTerminus = () => {
let terminus;
if (localStorage.getItem("terminus") === null) {
terminus = [];
} else {
terminus = JSON.parse(localStorage.getItem("terminus"));
}
let directions;
if (localStorage.getItem("directions") === null) {
directions = [];
} else {
directions = JSON.parse(localStorage.getItem("directions"));
}
terminus.forEach(async(stop) => {
let API_URL =
"https://ckan.multimediagdansk.pl/dataset/c24aa637-3619-4dc2-a171-a23eec8f2172/resource/d3e96eb6-25ad-4d6c-8651-b1eb39155945/download/stopsingdansk.json";
let response = await fetch(API_URL);
let data = await response.json();
const {
stops,
stopId,
stopName,
stopCode,
zoneId
} = data;
let input = stop;
let ID;
let dataArr = [];
for (let i = 0; i < stops.length; i++) {
if (
stops[i].stopName === input &&
stops[i].stopCode === directions[terminus.indexOf(input)] &&
stops[i].zoneId === 1
) {
ID = stops[i].stopId;
dataArr = [ID, stops[i].stopName];
}
}
API_URL = `https://ckan2.multimediagdansk.pl/delays?stopId=${ID}`;
response = await fetch(API_URL);
data = await response.json();
const {
delay,
estimatedTime,
routeId,
headsign
} = data;
let times = [];
let routeIds = [];
let headsigns = [];
for (let i = 0; i < delay.length; i++) {
times.push(delay[i].estimatedTime);
routeIds.push(delay[i].routeId);
headsigns.push(delay[i].headsign);
}
routeIds.push(" ");
times.push(" ");
const cardDiv = document.createElement("div");
cardDiv.classList.add("card");
const stopNameDiv = document.createElement("div");
stopNameDiv.classList.add("stop-name-div");
cardDiv.appendChild(stopNameDiv);
const stopNameSpan = document.createElement("span");
stopNameSpan.innerText = dataArr[1];
stopNameSpan.classList.add("stop-name-span");
stopNameDiv.appendChild(stopNameSpan);
const scheduleDiv = document.createElement("div");
scheduleDiv.classList.add("schedule-div");
cardDiv.appendChild(scheduleDiv);
if (headsigns.length !== 0) {
routeIds.unshift("Line");
headsigns.unshift("Direction");
times.unshift("Departure");
}
const lineSpan = document.createElement("span");
lineSpan.innerText = routeIds.join("\n");
lineSpan.classList.add("line-span");
scheduleDiv.appendChild(lineSpan);
const dirSpan = document.createElement("span");
dirSpan.innerText = headsigns.join("\n");
dirSpan.classList.add("dir-span");
scheduleDiv.appendChild(dirSpan);
const timeSpan = document.createElement("span");
timeSpan.innerText = times.join("\n");
timeSpan.classList.add("time-span");
scheduleDiv.appendChild(timeSpan);
const buttonsDiv = document.createElement("div");
buttonsDiv.classList.add("buttons-div");
cardDiv.appendChild(buttonsDiv);
const deleteButton = document.createElement("button");
deleteButton.innerHTML = '<i class="fas fa-trash"></i>';
deleteButton.classList.add("delete-button");
buttonsDiv.appendChild(deleteButton);
const dirButton = document.createElement("button");
dirButton.innerHTML = '<i class="fas fa-retweet"></i>';
dirButton.classList.add("reverse-button");
buttonsDiv.appendChild(dirButton);
stopList.appendChild(cardDiv);
});
};
document.addEventListener("DOMContentLoaded", getTerminus);
Terminus contains stop names, and directions contains direction codes.
On refresh, it fetches data from API based on stop name and direction, and displays a card with departure time etc.
The problem is, on closing and re-opening the page cards are sometimes displayed in a wrong order. I have found out, that as time between closing and opening lengthens, the probability of this occurring gets higher. After simple refresh everything is in correct order.
Does it have something to do with browser cache? Has anyone had similar issue or knows what's going on?
Alright, as #Yoshi stated, it was insequential promise error. I managed to fix it by using reduce().
Here are the threads that helped me
Resolve promises one after another (i.e. in sequence)?
Why Using reduce() to Sequentially Resolve Promises Works
i really need help.
How can i multiple embed into one message instead of sending 1 by 1?
if (msg.content.startsWith(prefix + "find")) {
const item = game.data.members;
const GQ = msg.content.split(' ').slice(1);
let ign;
let gq;
for (var i = 0; i < item.length; i++) {
if (item[i].task_finished_week < GQ) {
ign = item[i].name;
gq = item[i].task_finished_week;
const embed = new Discord.RichEmbed()
.setTitle(ign)
.addField('Weekly GQ', gq);
msg.channel.send({ embed });
}
}
I am working on a program in javascript for speech to text and text to speech. I try to capture the spoken text in a variable and process it in a database to find an answer. the value of my variable is always 0.
my question is how can i put the spoken text in a variable in js and edit it in PHP? is it possible? am I having trouble with semantic?
Thank you in advance.
below the code, myVar is a variable that always gets o value
var myvar = '';
var name = "";
var lengthOfName = name.length;
var transcript = '';
window.SpeechRecognition = window.webkitSpeechRecognition ||
window.SpeechRecognition;
let finalTranscript = '';
let recognition = new window.SpeechRecognition();
//let p = document.createElement('p');
//const words = document.querySelector('.words');
//words.appendChild(p);
recognition.interimResults = true;
recognition.maxAlternatives = 10;
recognition.continuous = true;
var testvar = "ggggggg";
recognition.onresult = (event) => {
let interimTranscript = '';
for (let i = event.resultIndex, len = event.results.length; i < len; i++) {
var transcript = event.results[i][0].transcript;
//transcript.replace("\n", "<br>");
if (event.results[i].isFinal) {
myvar = transcript;
//document.getElementById("text").value=myvar;
finalTranscript += transcript;
//p = document.createElement('p');
//words.appendChild(p);
} else {
interimTranscript += transcript;
myvar = transcript;
}
}
document.querySelector('#demo').innerHTML = finalTranscript + '<i
style = "color:#000d1a;" > ' + interimTranscript +' < />';
//document.querySelector('#demo').innerHTML += "\r\n";
const btn = document.querySelector('.talk');
const content = document.querySelector('.content');
const greetings = [
'If you are good im good to 😉',
'Im doin alright',
'Im tired 😴'
];
const weather = [
'Ask the weatherman!',
'I recommend checking your phone or the news '
];
const name = [
'My name is techwaala',
'its techwaala, because I love to code!'
];
const hello = [
'Why hello! How are you doing today?',
'Hey there How are you?'
]
const hru = [
'thats great!',
'Im so sorry to hear that',
'Feel better soon!'
]
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.onstart = function() {
console.log('voice is activated speak into the mic');
};
recognition.onresult = function(event) {
const current = event.resultIndex;
const transcript = event.results[current][0].transcript;
content.textContent = transcript;
readOutLoud(transcript);
}
btn.addEventListener('click', () => {
recognition.start();
});
function readOutLoud(message) {
const speech = new SpeechSynthesisUtterance();
speech.text = 'I dont know what you said';
if(message.includes('how are you')) {
const finalText =
greetings[Math.floor(Math.random() * greetings.length)];
speech.text = finalText;
}
if(['hey', 'hi', 'hello', 'hi there', 'hey there', 'hi techwala', 'hey techwala','hello techwala']
.some(word => message.includes(word))) {
const finalText = hello[Math.floor(Math.random() * hello.length)];
speech.text = finalText;
}
if(['whats your name', 'your name']
.some(word => message.includes(word))) {
const finalText = name[Math.floor(Math.random() * name.length)];
speech.text = finalText;
}
if(['how\'s the weather', 'what\'s the weather like', 'is it sunny', 'is it raining', 'is it cloudy', 'is it snowing']
.some(word => message.includes(word))) {
const finalText = weather[Math.floor(Math.random() * weather.length)];
speech.text = finalText;
}
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
I'm working on a webpage which talks when you say something. Its default is speaking in US Male but what if I wanted to change the accent to let's say UK Female or French Male? I tried using responsive voice.org but that isn't working for me. How would I do this? Also, I didn't insert the HTML into this snippet because I thought that the JavaScript would be the only necessary thing to look at.
Use speechSynthesis
There is a nice example in the docs, but essentially something like this if you were to hardcode the voice:
var synth = window.speechSynthesis;
// get voices
var voices = synth.getVoices();
// when voices have finished loading
synth.onvoiceschanged = function() {
var sayThis = new SpeechSynthesisUtterance('Hi how are you?');
sayThis.onend = function(event) {
console.log('SpeechSynthesisUtterance.onend');
}
sayThis.onerror = function(event) {
console.error('SpeechSynthesisUtterance.onerror');
}
var selectedVoice = 'Google UK English Female';
for (var i = 0; i < voices.length; i++) {
if (voices[i].name === selectedVoice) {
sayThis.voice = voices[i];
break;
}
}
sayThis.pitch = 1;
sayThis.rate = 1;
synth.speak(sayThis);
}