Uncaught SyntaxError: Identifier ‘url’ has already been declared

I have used Javascript to access the Google-text-to-speech API for over a year. But suddenly it stopped working getting the error “Uncaught SyntaxError: Identifier ‘url’ has already been declared texttospeech.js:1”. I don’t see any obvious errors. I can see the script is being enqueued for the page correctly, but it does not execute the script due to the syntax error. I added a console.log command to the first line of the script and when I use the Chrome Inspect Tool, nothing shows up in the console other than the uncaught syntax error. Has anyone else run into this? Here is copy of the script, any help would be greatly appreciated.

console.log("BEFORE!")
// // Declare a variable to store the access Token
let accessToken

// Get the current WindowURL.
const url = window.location.href;let url = window.location.href;

function parseAccessTokenFromUrl(url) {
  // Get the current URL.
  const urlObject = new URL(url);

  // Get the hash fragment of the URL.
  const hashFragment = urlObject.hash;

  // Remove the leading # character from the hash fragment.
  const hashFragmentWithoutHash = hashFragment.substring(1);

  // Find the index of the &token_type parameter in the hash fragment.
  const tokenTypeIndex = hashFragmentWithoutHash.indexOf('&token_type');

  // Extract the substring of the hash fragment from the index of the #access_token= sign to the index of the &token_type parameter.
  const extractedAccessToken = hashFragmentWithoutHash.substring(hashFragmentWithoutHash.indexOf('#access_token=') + 14, tokenTypeIndex);

  // Assign the extracted access token to the global variable
  accessToken = extractedAccessToken;

}

// Get the input variables from the form
// Get the user-entered text
      

// Console Log the values to be passed
 console.log('Access token:', accessToken);

 console.log(xhr.getAllResponseHeaders());


 function displaySliderValue(slider) {
  // Get the ID of the slider
  const sliderId = slider.id;

  // Display the slider value in the DOM
  if (sliderId === 'pitchSlider') {
    document.getElementById('pitchValue').textContent = slider.value;
  } else if (sliderId === 'speedSlider') {
    document.getElementById('speedValue').textContent = slider.value;
  } else {
    // Handle unknown slider
  }
}

// Reset the Slider Values to the default Values
const resetButton = document.getElementById('reset-Button').addEventListener('click', () => {
  // Get the default pitch and speed values
  const defaultPitchRate = 0;
  const defaultSpeakingRate = 1;

  // Set the slider values to the default values
  document.getElementById('pitchSlider').value = defaultPitchRate;
  document.getElementById('speedSlider').value = defaultSpeakingRate;

  // Update the slider values in the DOM
  displaySliderValue(document.getElementById('pitchSlider'));
  displaySliderValue(document.getElementById('speedSlider'));
});


const playButton = document.getElementById('play-button');
playButton.addEventListener('click', async () => {
  // Play the text
  const text = document.getElementById('textInput').value;

  // Get the selected voice language
  const selectedVoice = document.getElementById('voiceSelect').value;

  // Get the selected language code
  const selectedLanguage = document.getElementById('languageSelect').value;

  // Get the selected pitch value (0-2)
  const pitchRate = parseFloat(document.getElementById('pitchSlider').value);

  // Get the selected speed value (0.25-4)
  const speakingRate = parseFloat(document.getElementById('speedSlider').value);


  console.log('Text input:', text);
  console.log('Selected voice:', selectedVoice);
  console.log('Selected language code:', selectedLanguage);
  console.log('Voice pitch:', pitchRate);
  console.log('Playback speed:', speakingRate);
  

  try {
    const response = await fetch("https://texttospeech.googleapis.com/v1/text:synthesize", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": Bearer ${accessToken},
      },
      body: JSON.stringify({
        "input": {
          "text": ${text}
        }, // Enclose the text value in quotes
        "voice": {
          "name": ${selectedVoice},
          "languageCode": ${selectedLanguage}
        }, // Enclose the selectedVoice value in quotes
        "audioConfig": {
          "audioEncoding": "MP3",
          "speakingRate": ${speakingRate},
          "pitch": ${pitchRate} 
        },
      }),
    });

    // Create an Audio object from the audioContent and play it
    
    const audioData = await response.json();
    const byteCharacters = atob(audioData.audioContent);
    const byteArray = new Uint8Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteArray[i] = byteCharacters.charCodeAt(i);
    }
    
    const blob = new Blob([byteArray], { type: 'audio/mpeg' });
    const audio = new Audio(URL.createObjectURL(blob));
    
    // Play the audio
    audio.play();
    
    //Log the audioContent
    console.log('Audio-Data:', audio);}
    catch (error) {
    console.error('Error:', error);
  }
});



    // Download the text as audio
const downloadButton = document.getElementById('download-button');
downloadButton.addEventListener('click', async () => {
  // Download the text as audio
  const text = document.getElementById('textInput').value;

  // Get the selected voice language
  const selectedVoice = document.getElementById('voiceSelect').value;
   
  // Get the selected language code
  const selectedLanguage = document.getElementById('languageSelect').value;

  // Get the selected pitch value (0-2)
  const pitchRate = parseFloat(document.getElementById('pitchSlider').value);

  // Get the selected speed value (0.25-4)
  const speakingRate = parseFloat(document.getElementById('speedSlider').value);

  console.log('Text input:', text);
  console.log('Selected voice:', selectedVoice);
  console.log('Voice pitch:' , pitchRate);
  console.log('Playback speed:', speakingRate);
  console.log('Access Token:', accessToken) 
  try {
    const response = await fetch("https://texttospeech.googleapis.com/v1/text:synthesize", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": Bearer ${accessToken},
      },
      body: JSON.stringify({
      "input": { 
          "text": ${text}
          }, // Enclose the text value in quotes
      "voice": { 
          "name": ${selectedVoice},
          "languageCode": ${selectedLanguage}
          }, // Enclose the selectedVoice value in quotes
      "audioConfig": {
          "audioEncoding": "MP3",
          "speakingRate": ${speakingRate},
          "pitch": ${pitchRate} 
        },
    }),
    });

    const audioData = await response.json();
    const byteCharacters = atob(audioData.audioContent);
    const byteArray = new Uint8Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteArray[i] = byteCharacters.charCodeAt(i);
    }
    
    const blob = new Blob([byteArray], { type: 'audio/mpeg' });
    const anchor = document.createElement('a');
    anchor.href = URL.createObjectURL(blob);
    anchor.download = 'audio.mp3';
    anchor.click();
  } catch (error) {
    console.error('Error:', error);
  }
});

I tried swapping some of the “const” with “let” but it did not seem to make a difference. I also verified the oAuth2 functionality is working as expected. I also checked to see if the script was accidentally being loaded more than once but it was not. I originally thought maybe it is being caused by JS minifying, so I excluded textospeech.js.

  • This topic was modified 2 hours, 54 minutes ago by osheaw2.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer