My jQuery script is generating a blank wav file
I'm having problems with my code. It's suppose to get the text from a div and generate an audio file in wav. It can get a token and then pass that token plus the text from the <div> through a proxy PHP file to get around the cross-orgin block but it's generating a blank wav file. I'm able to generate text to speech using the example PHP files from github but can't on my server.
My PHP code:
<div class="text">This is an example text to generate a voice</div>
<button id="click">Click</button>
My jQuery code: jQuery(document).ready(function($) { $('#click').click(function() { var url = 'https://eastus.api.cognitive.microsoft.com/sts/v1.0/issueToken'; var apiKey = 'xxxxx'; // Replace with your actual API key
$.ajax({
url: url,
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Ocp-Apim-Subscription-Key', apiKey);
},
success: function(token) {
var proxyUrl = 'http://xxxxx/aivoice-proxy.php';
var text = $('.text').text(); // Get the text from the div with class "text"
$.ajax({
url: proxyUrl,
type: 'POST',
data: {
token: token,
text: text
},
dataType: 'text',
success: function(data) {
// Trigger file download
var a = document.createElement('a');
a.href = 'data:audio/wav;base64,' + btoa(data);
a.download = 'generated_voice.wav';
a.click();
},
error: function(xhr, status, error) {
console.error('Error occurred while generating the voice. Status:', status);
}
})
},
error: function(xhr, status, error) {
console.error('Error occurred while retrieving the token. Status:', status);
}
});
});
});
My aivoice-proxy.php file: <?php // Get the token, text, and subscription key from the request $token = $_POST['token']; $text = $_POST['text']; $subscriptionKey = 'xxxxxxx'; // Replace with your actual Azure subscription key
// Set the Azure endpoint URL $url = 'https://xxxxx.cognitiveservices.azure.com/sts/v1.0/issuetoken';
// Create an HTTP POST request to the Azure endpoint $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $text); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $token, 'Content-Type: application/ssml+xml', 'X-Microsoft-OutputFormat: audio-16khz-128kbitrate-mono-mp3', 'Ocp-Apim-Subscription-Key: ' . $subscriptionKey ));
// Execute the request and get the response $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session curl_close($ch);
// Check if the request was successful if ($httpCode === 200) { // Set the appropriate headers for file download header('Content-Type: audio/mpeg'); header('Content-Disposition: attachment; filename="generated_voice.mp3"');
// Output the response directly echo $response; } else { // Return an error message http_response_code($httpCode); echo 'Error occurred while generating the voice.'; } ?>