Overview

Speech generation in Suonora involves:

  • Text Input: The text you want to convert to speech
  • Voice Selection: Choosing from available voices
  • Audio Output: Receiving the generated audio file

JavaScript SDK

The JavaScript SDK provides the easiest way to integrate Suonora into your Node.js applications.

Installation

npm install suonora-sdk

Basic Usage

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();

Advanced Usage with Options

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();

Error Handling

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;
  }
}

Python

Python provides a straightforward way to interact with the Suonora API using the requests library.

Installation

pip install requests

Basic Usage

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()

Advanced Usage with Options

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()

Error Handling

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()

Java

Java applications can use the HttpClient to interact with the Suonora API.

Basic Usage

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();
    }
}

Advanced Usage with Options

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();
    }
}

Error Handling

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

cURL is perfect for testing the API or integrating with shell scripts.

Basic Usage

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

Advanced Usage with Options

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

Base64 Response Format

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

Error Handling

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

Best Practices

Text Preparation

  • Punctuation: Use proper punctuation to help the AI understand sentence structure
  • Length: Keep individual requests under 4,096 characters for best results
  • Language: Ensure text is in a language supported by your chosen voice
  • Formatting: Remove unnecessary formatting and special characters

Voice Selection

  • Consistency: Use the same voice throughout your application for brand consistency
  • Testing: Test different voices with your specific content
  • Quality: Use legacy-v2.5 for higher quality audio when needed

Performance Optimization

  • Caching: Cache generated audio for repeated text
  • Batch Processing: Process multiple requests efficiently
  • Error Handling: Implement proper error handling and retry logic
  • Rate Limits: Respect API rate limits and implement backoff strategies

File Management

  • Formats: Choose appropriate audio formats (MP3 for compatibility, Opus for efficiency)
  • Storage: Implement proper file storage and cleanup
  • Naming: Use descriptive filenames for generated audio files

Common Use Cases

E-learning Applications

// 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
});

Accessibility Features

# 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

Content Creation

# 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

Next Steps

Now that you understand the essentials of creating speech with the Suonora API, you can: