let apiKey = '';
function convertToSpeech() {
const textToConvert = document.getElementById('inputText').value.trim();
alert(`Text "${textToConvert}" will be converted to speech using the API.`);
apiKey = prompt('Enter your API key:').trim();
const xhr = new XMLHttpRequest();
const url = 'https://cloudlabs-text-to-speech.p.rapidapi.com/synthesize';
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-RapidAPI-Key', apiKey);
xhr.setRequestHeader('X-RapidAPI-Host', 'cloudlabs-text-to-speech.p.rapidapi.com');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
document.getElementById('audioPlayer').src = response.audio_url;
} else {
console.error('Error:', xhr.status);
}
}
};
const params = `voice_code=en-US-1&text=${textToConvert}&speed=1.00&pitch=1.00&output_type=audio_url`;
xhr.send(params);
}
// Creating HTML elements programmatically
const h1 = document.createElement('h1');
h1.textContent = 'Text to Speech';
const p = document.createElement('p');
p.textContent = 'Convert your text to speech using the service.';
const inputDiv = document.createElement('div');
inputDiv.style.width = '60vw';
inputDiv.style.backgroundColor = 'white';
inputDiv.style.border = '1px solid black';
inputDiv.style.margin = '20px';
inputDiv.style.padding = '20px';
const inputHeader = document.createElement('h3');
inputHeader.textContent = 'Enter text to convert';
const inputText = document.createElement('input');
inputText.style.width = '50vw';
inputText.value = 'Hello, what is your name?';
inputText.id = 'inputText';
const convertBtn = document.createElement('button');
convertBtn.textContent = 'Convert';
convertBtn.className = 'ab-normbutton';
convertBtn.onclick = convertToSpeech;
inputDiv.appendChild(inputHeader);
inputDiv.appendChild(inputText);
inputDiv.appendChild(convertBtn);
const audioDiv = document.createElement('div');
audioDiv.style.width = '60vw';
audioDiv.style.backgroundColor = '#ffffcc';
audioDiv.style.border = '1px solid black';
audioDiv.style.margin = '20px';
audioDiv.style.padding = '20px';
const audioHeader = document.createElement('h3');
audioHeader.textContent = 'Audio';
const audioPlayer = document.createElement('audio');
audioPlayer.id = 'audioPlayer';
audioPlayer.controls = true;
audioDiv.appendChild(audioHeader);
audioDiv.appendChild(audioPlayer);
// Appending elements to the document body
document.body.appendChild(h1);
document.body.appendChild(p);
document.body.appendChild(inputDiv);
document.body.appendChild(audioDiv);