Learn the essentials of creating speech with the Suonora API using different programming languages and tools.
npm install suonora-sdk
import { Suonora } from "suonora-sdk";
const suonora = new Suonora({
apiKey: "your-api-key-here",
});
async function createSpeech() {
try {
const speech = await suonora.speech.create({
input: "Hello, this is a test of the Suonora text-to-speech API.",
voice: "axel",
model: "legacy-v2.5",
});
// Save the audio file
const fs = require("fs");
fs.writeFileSync("output.mp3", speech.audio);
console.log("Speech created successfully!");
} catch (error) {
console.error("Error creating speech:", error);
}
}
createSpeech();
import { Suonora } from "suonora-sdk";
const suonora = new Suonora({
apiKey: "your-api-key-here",
});
async function createAdvancedSpeech() {
try {
const speech = await suonora.speech.create({
input:
"Welcome to our application! This demonstrates advanced speech generation.",
voice: "axel",
model: "legacy-v2.5",
style: "cheerful",
styleDegree: 1.2,
});
// Handle different response formats
if (speech.response_format === "mp3") {
const fs = require("fs");
fs.writeFileSync("output.mp3", speech.audio);
} else if (speech.response_format === "opus") {
const fs = require("fs");
fs.writeFileSync("output.opus", speech.audio);
}
console.log("Advanced speech created successfully!");
} catch (error) {
console.error("Error creating speech:", error);
}
}
createAdvancedSpeech();
import { Suonora } from "suonora-sdk";
const suonora = new Suonora({
apiKey: "your-api-key-here",
});
async function createSpeechWithErrorHandling() {
try {
const speech = await suonora.speech.create({
input: "Hello world!",
voice: "axel",
});
console.log("Speech created successfully!");
return speech;
} catch (error) {
if (error.status === 401) {
console.error("Authentication failed. Please check your API key.");
} else if (error.status === 400) {
console.error("Invalid request:", error.message);
} else if (error.status === 429) {
console.error("Rate limit exceeded. Please try again later.");
} else {
console.error("Unexpected error:", error.message);
}
throw error;
}
}
requests
library.
pip install requests
import requests
import json
def create_speech():
url = "https://api.suonora.com/v1/audio/speech"
headers = {
"Authorization": f"Bearer your-api-key-here",
"Content-Type": "application/json"
}
data = {
"input": "Hello, this is a test of the Suonora text-to-speech API.",
"voice": "axel",
"model": "legacy-v2.5",
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
# Save the audio file
with open("output.mp3", "wb") as f:
f.write(response.content)
print("Speech created successfully!")
except requests.exceptions.RequestException as e:
print(f"Error creating speech: {e}")
if __name__ == "__main__":
create_speech()
import requests
import json
import base64
def create_advanced_speech():
url = "https://api.suonora.com/v1/audio/speech"
headers = {
"Authorization": f"Bearer your-api-key-here",
"Content-Type": "application/json"
}
data = {
"input": "Welcome to our application! This demonstrates advanced speech generation.",
"voice": "axel",
"model": "legacy-v2.5",
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
# Handle different response formats
if data["response_format"] == "mp3":
with open("output.mp3", "wb") as f:
f.write(response.content)
elif data["response_format"] == "opus":
with open("output.opus", "wb") as f:
f.write(response.content)
print("Advanced speech created successfully!")
except requests.exceptions.RequestException as e:
print(f"Error creating speech: {e}")
def create_speech_with_base64():
url = "https://api.suonora.com/v1/audio/speech"
headers = {
"Authorization": f"Bearer your-api-key-here",
"Content-Type": "application/json"
}
data = {
"input": "This will return base64 encoded audio.",
"voice": "axel",
"model": "legacy-v2.5",
"response_format": "base64"
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
result = response.json()
audio_data = base64.b64decode(result["audio"])
with open("output.mp3", "wb") as f:
f.write(audio_data)
print("Base64 speech created successfully!")
except requests.exceptions.RequestException as e:
print(f"Error creating speech: {e}")
if __name__ == "__main__":
create_advanced_speech()
create_speech_with_base64()
import requests
import json
def create_speech_with_error_handling():
url = "https://api.suonora.com/v1/audio/speech"
headers = {
"Authorization": f"Bearer your-api-key-here",
"Content-Type": "application/json"
}
data = {
"input": "Hello world!",
"voice": "axel",
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
with open("output.mp3", "wb") as f:
f.write(response.content)
print("Speech created successfully!")
return response.content
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
print("Authentication failed. Please check your API key.")
elif e.response.status_code == 400:
print(f"Invalid request: {e.response.text}")
elif e.response.status_code == 429:
print("Rate limit exceeded. Please try again later.")
else:
print(f"HTTP error: {e}")
raise
except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
raise
if __name__ == "__main__":
create_speech_with_error_handling()
HttpClient
to interact with the Suonora API.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;
public class SuonoraSpeech {
private static final String API_KEY = "your-api-key-here";
private static final String API_URL = "https://api.suonora.com/v1/audio/speech";
public static void createSpeech() {
try {
HttpClient client = HttpClient.newHttpClient();
String jsonBody = """
{
"input": "Hello, this is a test of the Suonora text-to-speech API.",
"voice": "axel",
"model": "legacy-v2.5"
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<byte[]> response = client.send(request,
HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() == 200) {
Files.write(Paths.get("output.mp3"), response.body());
System.out.println("Speech created successfully!");
} else {
System.out.println("Error: " + response.statusCode());
}
} catch (Exception e) {
System.err.println("Error creating speech: " + e.getMessage());
}
}
public static void main(String[] args) {
createSpeech();
}
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class SuonoraAdvancedSpeech {
private static final String API_KEY = "your-api-key-here";
private static final String API_URL = "https://api.suonora.com/v1/audio/speech";
public static void createAdvancedSpeech() {
try {
HttpClient client = HttpClient.newHttpClient();
String jsonBody = """
{
"input": "Welcome to our application! This demonstrates advanced speech generation.",
"voice": "axel",
"model": "legacy-v2.5",
"response_format": "mp3",
"speed": 1.0
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<byte[]> response = client.send(request,
HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() == 200) {
Files.write(Paths.get("output.mp3"), response.body());
System.out.println("Advanced speech created successfully!");
} else {
System.out.println("Error: " + response.statusCode());
}
} catch (Exception e) {
System.err.println("Error creating speech: " + e.getMessage());
}
}
public static void createSpeechWithBase64() {
try {
HttpClient client = HttpClient.newHttpClient();
String jsonBody = """
{
"input": "This will return base64 encoded audio.",
"voice": "axel",
"model": "legacy-v2.5",
"response_format": "base64"
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
// Parse JSON response to get base64 audio
String responseBody = response.body();
// You would need a JSON parser here to extract the "audio" field
// For simplicity, assuming the response is just the base64 string
byte[] audioData = Base64.getDecoder().decode(responseBody);
Files.write(Paths.get("output.mp3"), audioData);
System.out.println("Base64 speech created successfully!");
} else {
System.out.println("Error: " + response.statusCode());
}
} catch (Exception e) {
System.err.println("Error creating speech: " + e.getMessage());
}
}
public static void main(String[] args) {
createAdvancedSpeech();
createSpeechWithBase64();
}
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;
public class SuonoraSpeechWithErrorHandling {
private static final String API_KEY = "your-api-key-here";
private static final String API_URL = "https://api.suonora.com/v1/audio/speech";
public static void createSpeechWithErrorHandling() {
try {
HttpClient client = HttpClient.newHttpClient();
String jsonBody = """
{
"input": "Hello world!",
"voice": "axel",
"model": "legacy-v2.5"
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<byte[]> response = client.send(request,
HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() == 200) {
Files.write(Paths.get("output.mp3"), response.body());
System.out.println("Speech created successfully!");
} else {
handleError(response.statusCode(), new String(response.body()));
}
} catch (Exception e) {
System.err.println("Error creating speech: " + e.getMessage());
}
}
private static void handleError(int statusCode, String responseBody) {
switch (statusCode) {
case 401:
System.err.println("Authentication failed. Please check your API key.");
break;
case 400:
System.err.println("Invalid request: " + responseBody);
break;
case 429:
System.err.println("Rate limit exceeded. Please try again later.");
break;
default:
System.err.println("Unexpected error: " + statusCode + " - " + responseBody);
}
}
public static void main(String[] args) {
createSpeechWithErrorHandling();
}
}
curl -X POST "https://api.suonora.com/v1/audio/speech" \
-H "Authorization: Bearer your-api-key-here" \
-H "Content-Type: application/json" \
-d '{
"input": "Hello, this is a test of the Suonora text-to-speech API.",
"voice": "axel",
"model": "legacy-v2.5"
}' \
--output output.mp3
curl -X POST "https://api.suonora.com/v1/audio/speech" \
-H "Authorization: Bearer your-api-key-here" \
-H "Content-Type: application/json" \
-d '{
"input": "Welcome to our application! This demonstrates advanced speech generation.",
"voice": "axel",
"model": "legacy-v2.5",
"response_format": "mp3",
"speed": 1.0
}' \
--output output.mp3
curl -X POST "https://api.suonora.com/v1/audio/speech" \
-H "Authorization: Bearer your-api-key-here" \
-H "Content-Type: application/json" \
-d '{
"input": "This will return base64 encoded audio.",
"voice": "axel",
"model": "legacy-v2.5",
"response_format": "base64"
}' \
--output response.json
curl -X POST "https://api.suonora.com/v1/audio/speech" \
-H "Authorization: Bearer your-api-key-here" \
-H "Content-Type: application/json" \
-d '{
"input": "Hello world!",
"voice": "axel",
"model": "legacy-v2.5"
}' \
--output output.mp3 \
--write-out "HTTP Status: %{http_code}\n" \
--silent --show-error
legacy-v2.5
for higher quality audio when needed// Generate speech for educational content
const educationalText =
"The capital of France is Paris. It is located in the north-central part of the country.";
const speech = await suonora.speech.create({
input: educationalText,
voice: "axel",
model: "legacy-v2.5",
speed: 0.9, // Slightly slower for educational content
});
# Generate speech for screen readers
def generate_accessibility_speech(text):
response = requests.post(
"https://api.suonora.com/v1/audio/speech",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"input": text,
"voice": "axel",
"model": "legacy-v2.5",
"speed": 1.0
}
)
return response.content
# Generate speech for podcast content
curl -X POST "https://api.suonora.com/v1/audio/speech" \
-H "Authorization: Bearer your-api-key-here" \
-H "Content-Type: application/json" \
-d '{
"input": "Welcome to our weekly podcast. Today we will discuss the latest developments in AI technology.",
"voice": "axel",
"model": "legacy-v2.5",
"speed": 1.0
}' \
--output podcast_intro.mp3