Add in google text to speech api to godot 4

Godot Version

Godot version 4.2.1

Question

Hello!
I am trying to add in google text to speech api to a game. https://cloud.google.com/text-to-speech?hl=en
I tried using this script to use the api but it gives me a error when I try to run it.

extends Node

Your Google API key

var api_key = “YOUR_API_KEY_HERE”

URL for the Google Text-to-Speech API

var tts_url = “https://texttospeech.googleapis.com/v1/text:synthesize?key=” + api_key

Function to synthesize speech from text

func synthesize_speech(text: String):
# JSON request body
var body = {
“input”: {“text”: text},
“voice”: {“languageCode”: “en-US”, “ssmlGender”: “NEUTRAL”, “name”: “en-US-Wavenet-D”},
“audioConfig”: {“audioEncoding”: “MP3”}
}

# Create an instance of JSON
var json = JSON.new()
# Convert the dictionary into a JSON string
var json_body = json.print(body)

# Create an HTTPRequest node
var http_request = HTTPRequest.new()
add_child(http_request)

# Connect the request_completed signal to a callable
http_request.connect("request_completed", Callable(self, "_on_request_completed"))

# Configure the HTTP request node for a POST request with JSON data
http_request.request(tts_url, ["Content-Type: application/json"], json_body, "POST")

Callback function to process the Google API’s response

func _on_request_completed(result, response_code, headers, body):
var json = JSON.new() # Create a JSON instance to handle JSON parsing
var response = json.parse(body.get_string_from_utf8())
if response.error != OK:
print("JSON parsing error: ", response.error)
return

var data = response.result

# Check if the API returned an error
if data.has("error"):
	print("Error: ", data["error"])
else:
	# Assuming the response is successful, handle the audio data
	print("Speech synthesis successful, handle audio data here.")
	# Here, you might save the audio to a file or stream it directly

Example usage

func _ready():
synthesize_speech(“Hello, how can I assist you today?”)

This is the error it gives me when I try to run it.
Invalid call. Nonexistent function ‘print’ in base ‘JSON’.

From the way this code is write probably was done in Godot 3, but you’re using Godot 4 that had lot of breaking changes. The function you want is called stringify now, i recommend you read more about Godot 4 or use Godot 3 instead.

JSON — Godot Engine (stable) documentation in English

1 Like

thanks