Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

'UNAUTHORIZED ERROR' using google cloud text to speech API

Hi,

I am using the following code to see if i can use the text to speech api. I am getting a consistent 401 authorization error. I plan to use google cloud text to speech in my existing web app, which was originally using web speech api. I am unable to get the google api to work. Please assist. Thanks. Here is the code I am using:

<!DOCTYPE html>
<html>
<head>
<title>Text-to-Speech Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Text-to-Speech Example</h1>
<textarea id="inputText" rows="4" cols="50"></textarea>
<button onclick="synthesize()">Synthesize</button>
<audio id="audio" controls></audio>
<script>
function synthesize() {
var text = document.getElementById('inputText').value;
$.ajax({
url: 'https://texttospeech.googleapis.com/v1/text:synthesize',
type: 'POST',
data: JSON.stringify({
input: { text: text },
voice: { languageCode: 'en-US', ssmlGender: 'FEMALE' },
audioConfig: { audioEncoding: 'MP3' }
}),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer THIS IS WHERE MY API KEY GOES'
},
success: function (data) {
var audioUrl = 'data:audio/mp3;base64,' + data.audioContent;
document.getElementById('audio').src=audioUrl;
document.getElementById('audio').play();
},
error: function (error) {
console.error('Error:', error);
}
});
}
</script>
</body>
</html>

0 1 1,521
1 REPLY 1

Hi @ashchopra,

Welcome to Google Cloud Community.

You are experiencing a problem with the authentication of your Google Cloud API key, according to the 401 authorization error that you are receiving. You might attempt the following solutions to troubleshoot this problem:

  • Verify in your Google Cloud Console by navigating to the "APIs & Services" section and then selecting "Credentials".

  • Verify your Google Cloud Console to make sure the Text-to-Speech API is enabled.

  • Verify that the API key value in the Authorization header is formatted correctly.

  • Verify if it fixes the problem, you can also try to generate a new API key and use that in your code.

Hope this will help you.