Advertisement
nrzmalik

Text to Speech Arabic Language Recognition

Oct 17th, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.15 KB | Source Code | 0 0
  1. let recognition;
  2. let recognizing = false;
  3. let currentStorylineVar = '';
  4. let currentTranscript = '';
  5. let previousTranscript = '';
  6.  
  7. const initializeSpeechRecognition = () => {
  8.   window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  9.  
  10.   if (!window.SpeechRecognition) {
  11.     alert("Your browser does not support the Web Speech API. Please try with a different browser.");
  12.     return;
  13.   }
  14.  
  15.   recognition = new SpeechRecognition();
  16.   recognition.lang = 'ar-SA';  // Setting the language to Arabic (Saudi Arabia)
  17.   recognition.interimResults = true;
  18.  
  19.   recognition.addEventListener('start', () => {
  20.     recognizing = true;
  21.     console.log('Speech recognition started');
  22.   });
  23.  
  24.   recognition.addEventListener('end', () => {
  25.     recognizing = false;
  26.     console.log('Speech recognition ended');
  27.     updateStorylineVariable();
  28.   });
  29.  
  30.   recognition.addEventListener('result', (event) => {
  31.     let interimTranscript = '';
  32.     for (let i = event.resultIndex; i < event.results.length; i++) {
  33.       const transcript = event.results[i][0].transcript;
  34.       if (event.results[i].isFinal) {
  35.         currentTranscript += transcript + ' ';
  36.       } else {
  37.         interimTranscript += transcript;
  38.       }
  39.     }
  40.     const player = GetPlayer();
  41.     player.SetVar(currentStorylineVar, currentTranscript + interimTranscript);
  42.     console.log(`Interim text: ${currentTranscript + interimTranscript}`);
  43.   });
  44.  
  45.   recognition.addEventListener('error', (event) => {
  46.     console.error('Speech recognition error:', event.error);
  47.   });
  48. };
  49.  
  50. const updateStorylineVariable = () => {
  51.   const player = GetPlayer();
  52.   const finalTranscript = (previousTranscript + ' ' + currentTranscript.trim()).trim();
  53.   player.SetVar(currentStorylineVar, finalTranscript);
  54.   console.log(`Final text: ${finalTranscript}`);
  55.   previousTranscript = finalTranscript;
  56.   currentTranscript = '';
  57. };
  58.  
  59. const speechtotext = (storylineVar) => {
  60.   currentStorylineVar = storylineVar;
  61.  
  62.   if (!recognition) {
  63.     initializeSpeechRecognition();
  64.   }
  65.  
  66.   const player = GetPlayer();
  67.   previousTranscript = player.GetVar(currentStorylineVar) || '';
  68.  
  69.   recognition.start();
  70. };
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement