Quickstart Guide: Integrating Text-to-Speech with JavaScript

By PlateSpeak editorial team · Updated 2026-11-19

This guide details the integration of the PlateSpeak Text-to-Speech API using JavaScript, specifically designed for large restaurant chains and dining halls. It covers the essential steps to automate menu announcements, queue notifications, and digital signage scripts by replacing browser-based synthesis with a robust cloud endpoint. You will learn how to configure requests, manage voices, and handle audio formats within your existing infrastructure.

The documentation provides concrete code examples for Node.js and browser environments, along with precise parameters for speed, language, and format selection. It also outlines rate limits, error handling, and strategies for splitting long texts into valid segments. By following these instructions, your development team can reliably deploy audio notifications at scale without managing complex infrastructure.

Quickstart Guide: Integrating Text-to-Speech with JavaScript

Frequently asked questions

How do I install the OpenAI SDK for this API?

Install the official OpenAI SDK using your package manager, such as npm install openai. The SDK works by changing the base_url to https://api.sofortwin.cc/v1 and using your PlateSpeak key. This allows you to use standard methods like audio.speech.create without needing a proprietary client library.

What is the correct base_url for the API?

The correct base_url is https://api.sofortwin.cc/v1. Configure your SDK or HTTP client to point to this endpoint. This URL handles all requests, including speech generation and voice retrieval, ensuring compatibility with the standard OpenAI request shape for seamless integration into your existing workflows.

Can I use the same key for development and production?

Yes, you can use the same key for both environments. Each account has one active key that works across all applications. If needed, you can issue a new key at any time, which immediately invalidates the old one, allowing you to rotate credentials without downtime.

How do I specify the voice in the JSON body?

Include the voice parameter in your JSON body with one of the eight presets: aria, nova, luna, sage, felix, milo, atlas, or orion. For example, set "voice": "nova". The API ignores the language parameter if not provided, guessing from the script, but you can override it.

What happens if I exceed the rate limit?

The rate limit is 60 requests per minute per key. If you exceed this, requests may queue or fail. Requests are processed sequentially, so under load, you may experience delays. Failed requests are free.

Is the API key secure when stored in JS?

The key is sent in the Authorization header as a Bearer token. While secure for server-side use, storing it in client-side JavaScript exposes it to users. Use it in backend proxies for production. The key authenticates your account, and only one key is active at a time.

How do I handle asynchronous requests in Node.js?

Use async/await with the OpenAI SDK. Call the speech endpoint asynchronously to receive the audio file. Since requests are processed sequentially, under load, your promise may wait in a queue. Ensure your code handles potential delays gracefully without blocking other operations unnecessarily.

What is the maximum text length per request?

The maximum input text length is 4096 characters per request. For longer texts, split them into parts of up to 4096 characters and join the resulting audio files. Spaces and punctuation count toward the character limit, so plan your splits accordingly to avoid truncation.

Can I change the speed of the audio dynamically?

Yes, set the speed parameter between 0.25 and 4.0 in your request body. This adjusts the playback speed of the generated audio dynamically. The default speed is 1.0. Adjusting speed does not affect the character count or pricing.

How do I detect which language the API chose?

The API guesses the language from the script if not specified, defaulting to English for Latin text. You can explicitly set the language using an ISO code. The response does not explicitly state the detected language, so you must track your input parameters to know the result.

Are there examples for React or Vue?

No specific examples for React or Vue are provided. The API uses standard HTTP requests compatible with any JavaScript environment. You can use the OpenAI SDK or plain fetch calls within your framework’s lifecycle methods or hooks to integrate the TTS functionality seamlessly.

How do I convert the binary audio to a file?

The API returns audio in the requested format (mp3, wav, opus, flac, pcm). Write the binary response directly to a file on your server or save it in your application’s storage. The SDK handles the response parsing, so you just need to save the resulting buffer.

What is the default response format?

The default response format is mp3. You can specify other formats like wav, opus, flac, or pcm in your request. If not specified, the API defaults to mp3, which is suitable for most web and mobile applications requiring efficient compression and broad compatibility.

How do I rotate my API key?

Issue a new key from your account dashboard at any time. The new key becomes active immediately, and the old one stops working at once. This allows you to rotate keys without downtime. You can manage your key from the /get-api-key/ page on the site.

First request

curl

curl https://api.sofortwin.cc/v1/audio/speech \
  -H "Authorization: Bearer $TTS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"tts-1","voice":"aria","input":"Hello from the API.","response_format":"mp3"}' \
  --output hello.mp3

Python (openai)

from openai import OpenAI

client = OpenAI(base_url="https://api.sofortwin.cc/v1", api_key="tts-...")

with client.audio.speech.with_streaming_response.create(
    model="tts-1", voice="nova", input="Hello from Python.", response_format="mp3"
) as response:
    response.stream_to_file("hello.mp3")

Node.js (openai)

import OpenAI from "openai";
import fs from "node:fs";

const client = new OpenAI({ baseURL: "https://api.sofortwin.cc/v1", apiKey: process.env.TTS_API_KEY });
const res = await client.audio.speech.create({ model: "tts-1", voice: "milo", input: "Hello from Node.js." });
fs.writeFileSync("hello.mp3", Buffer.from(await res.arrayBuffer()));
voice
ariafemale
novafemale
lunafemale
sagefemale
felixmale
milomale
atlasmale
orionmale
language
arالعربية
zh中文
daDansk
nlNederlands
enEnglish
fiSuomi
frFrançais
deDeutsch
elΕλληνικά
heעברית
hiहिन्दी
itItaliano
ja日本語
ko한국어
msBahasa Melayu
noNorsk
plPolski
ptPortuguês
ruРусский
esEspañol
swKiswahili
svSvenska
trTürkçe

Getting Your API Key

Sound wave illustration for: Getting Your API Key

Access the /get-api-key/ page on sofortwin.cc to create your account. You can sign in with Google or use an email and password. Google sign-in includes a $0.50 trial credit valid for 7 days, while email accounts start with zero balance.

Once registered, navigate to the dashboard to view your unique API key and current usage statistics. This key authenticates all requests to the API base https://api.sofortwin.cc/v1.

Sign Up on the Portal

Sign Up on the Portal

Visit the sign-up page at https://sofortwin.cc/get-api-key/. Choose Google authentication for immediate trial credit or standard email registration. Accounts are specific to this domain.

Verification is immediate. No invoice or VAT details are required at this stage. Your account is ready for configuration upon completion.

  • Google sign-in grants $0.50 trial credit
  • Email/password accounts start with $0.00 balance
  • 7-day validity for trial credits

Locate Your Secret Key

Locate Your Secret Key

Your API key appears on the dashboard alongside your current balance and character count. It begins with the prefix 'tts-' and is used for all API calls.

Keep this key secure. It provides full access to your account's billing and generation capabilities.

  • Key format: tts-...
  • Displayed on the main dashboard
  • Used in Authorization header

Key Management and Rotation

One active key is permitted per account. You can issue a new key at any time via the dashboard.

Upon issuing a new key, the previous key becomes invalid immediately. Update your integration configuration promptly to avoid service interruption during rotation.

  • One active key per account
  • Old key stops instantly on rotation
  • Issue new key from dashboard

Basic Request Structure

Sound wave illustration for: Basic Request Structure

Configure your API client to send POST requests to the dedicated endpoint: https://api.sofortwin.cc/v1/audio/speech. This single URL handles all synthesis operations for the PlateSpeak service, replacing the need for multiple server endpoints.

Endpoint URL Configuration

Direct all requests to the specified base URL. Ensure your HTTP client is configured to handle JSON payloads and standard authentication headers for reliable connectivity.

JSON Body Parameters

The request body must include the model ("tts-1" or "tts-1-hd"), input text (max 4096 characters), and voice preset. Additional optional fields include response_format, speed (0.25–4.0), and language ISO code.

  • model: "tts-1" or "tts-1-hd"
  • input: string up to 4096 characters
  • voice: one of 8 available presets
  • response_format: mp3, wav, opus, flac, or pcm

Authorization Header Setup

Include your unique API key in the header as Authorization: Bearer tts-.... This key authenticates your account and tracks character usage against your balance. Rotate the key via the portal if needed; the old key stops immediately.

OpenAI SDK Compatibility

Sound wave illustration for: OpenAI SDK Compatibility

PlateSpeak’s API mirrors the OpenAI speech endpoint structure, allowing you to use the official OpenAI JavaScript SDK with minimal configuration. This compatibility ensures that existing integrations can be adapted quickly without rewriting core request logic.

Using the Official SDK

Install the standard openai npm package as you normally would. The library handles JSON serialization and response parsing efficiently for our endpoint.

Changing the Base URL

Initialize the client by setting baseURL to https://api.sofortwin.cc/v1. Pass your PlateSpeak key via the apiKey parameter. This redirects all standard TTS calls to our cloud infrastructure.

  • Base URL: https://api.sofortwin.cc/v1
  • Auth Header: Bearer tts-...

Standard Endpoint Usage

Call client.audio.speech.create() with your model, input, and voice parameters. The SDK returns the audio file directly, handling the binary response seamlessly for Node.js or browser environments.

Audio Format Selection

Sound wave illustration for: Audio Format Selection

The API supports five audio formats: mp3, wav, opus, flac, and pcm. Selecting the correct format ensures compatibility with your restaurant's digital signage players and queue notification systems. Each format balances file size, quality, and processing overhead differently.

MP3 for General Use

MP3 is the default and most widely supported format. It offers a good balance between file size and audio quality, making it ideal for standard menu announcements and queue updates. Use mp3 when you need broad compatibility with existing hardware.

WAV for High Quality

WAV provides uncompressed audio, ensuring the highest fidelity for your announcements. This format is suitable for high-end digital signage or environments where audio clarity is critical. Note that WAV files are larger than MP3, consuming more storage and bandwidth.

OPUS and FLAC Options

OPUS offers efficient compression with good quality, suitable for network-constrained environments. FLAC provides lossless compression, reducing file size without any quality loss. PCM is available for raw, uncompressed audio data. Choose these formats based on your specific storage and quality requirements.

Voice and Language Parameters

Sound wave illustration for: Voice and Language Parameters

Configure vocal delivery by selecting one of eight presets tailored for clear public address. Choose from female voices like Aria for warm narration or Nova for upbeat updates, or male options such as Atlas for neutral announcements or Orion for documentary-style depth. Each voice supports any of the 23 supported languages.

The system automatically guesses the language from the script if none is specified, defaulting to English for Latin text. However, explicitly setting the language code is required for non-English Latin scripts to ensure accurate pronunciation. Supported languages include Arabic, Chinese, German, Hindi, Japanese, Korean, Spanish, and others, ensuring consistent quality across diverse dining environments.

Selecting a Voice Preset

Choose from eight presets optimized for clarity in noisy dining halls. Female options include Aria (warm narrator), Nova (upbeat), Luna (soft storytelling), and Sage (calm instruction). Male options include Felix (energetic promo), Milo (conversational), Atlas (neutral news), and Orion (deep documentary).

All voices are derived from licensed recordings and carry an inaudible synthetic watermark. They are not custom-cloned and maintain a consistent tone suitable for automated menu announcements or queue notifications.

  • Aria: Warm, clear narrator
  • Nova: Bright, upbeat
  • Luna: Soft, storytelling
  • Sage: Calm, instructional
  • Felix: Energetic, promo
  • Atlas: Neutral, news
  • Orion: Deep, documentary

Setting the Language Code

Explicitly define the language parameter using ISO codes for non-English Latin texts to prevent defaulting to English pronunciation. The API supports 23 languages including Arabic, Chinese, Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, and Turkish.

Any voice can speak any supported language. If the language field is omitted, the system attempts to guess the language from the script, but explicit setting is recommended for reliability in multilingual chains.

Speed Adjustment Limits

Adjust the speed parameter between 0.25 and 4.0 to control playback rate. Faster speeds may reduce clarity in noisy environments, while slower speeds enhance comprehension for complex menu items or dietary information.

Balancing speed with voice selection ensures optimal listener experience across large teams and customer-facing displays without requiring additional configuration.

Voice and Language Parameters

Error Handling and Limits

Sound wave illustration for: Error Handling and Limits

PlateSpeak enforces a strict rate limit of 60 requests per minute per API key. New accounts without a top-up start at a reduced limit of 10 requests per minute. Exceeding these thresholds triggers HTTP 429 errors, requiring immediate backoff to avoid service disruption during high-volume menu announcements.

Rate Limit Management

Monitor your usage dashboard to track request velocity. If you approach the 60 requests/minute cap, implement local queuing to smooth out bursts. Failed requests are free and do not consume credit.

  • Standard limit: 60 requests/minute
  • Initial limit: 10 requests/minute
  • Failed requests are free but count against the limit

Handling HTTP Errors

Common errors include 400 (invalid JSON or voice ID), 401 (invalid API key), and 429 (rate limit exceeded). Always inspect the response body for specific error codes to distinguish between configuration mistakes and infrastructure limits.

Retry Logic for Requests

Implement exponential backoff for 429 and 500 errors. For 401 errors, verify your key in the portal immediately. Do not retry 400 errors without changing the request payload, as they indicate a permanent configuration issue.

Code Examples

Sound wave illustration for: Code Examples

The PlateSpeak API integrates seamlessly with standard JavaScript environments, allowing restaurant systems to generate audio for menu announcements and queue notifications. Below are concrete implementations for Node.js servers, client-side browsers, and command-line verification.

All examples use the tts-1 model with the aria voice. Replace YOUR_API_KEY with your key from the portal.

Node.js Fetch Example

Use the native fetch API for server-side generation. This method is ideal for backend services that process menu data before sending audio to digital signage displays.

Set the base_url in your OpenAI SDK client to https://api.sofortwin.cc/v1 to leverage the same request structure.

  • Max input length: 4096 characters per request.
  • Rate limit: 60 requests per minute per key.

Browser JavaScript Example

Client-side generation is possible but exposes your API key. Ensure your key has appropriate permissions or use a proxy for production dining hall environments.

The response returns a blob containing the audio file, which can be directly played by an HTML5 audio element.

Curl Command Example

Verify your integration and key validity using the command line before implementing in your application code.

Advanced Usage Patterns

Sound wave illustration for: Advanced Usage Patterns

For menu announcements exceeding 4,096 characters, split the input text into segments and process each individually. This ensures compliance with API limits.

Splitting Long Texts

Divide the script into chunks of up to 4,096 characters. Submit each chunk as a separate POST request to the speech endpoint. This prevents truncation and ensures the entire menu or instruction set is delivered.

  • Split at sentence boundaries to preserve semantic meaning.
  • Track character counts to stay within the 4,096 limit.
  • Maintain order by timestamp or sequence ID.

Joining Audio Segments

Receive individual audio files (MP3, WAV, or FLAC) for each segment. Concatenate these files in sequence using a standard audio library or command-line tool like FFmpeg. This creates a single, seamless announcement for your dining hall displays.

Batch Processing Requests

Send multiple synthesis requests concurrently to reduce latency. Monitor your rate limit of 60 requests per minute. Queue additional requests if the limit is reached, ensuring no audio segments are lost during high-volume menu updates.

  • Respect the 60 requests/minute limit per key.
  • Use queueing logic for burst traffic.
  • Verify all segments before joining.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. Your data remains yours, used solely to generate the requested audio file for that specific request.

Avatar of the voice aria
ariafemale
Avatar of the voice nova
novafemale
Avatar of the voice luna
lunafemale
Avatar of the voice sage
sagefemale
Avatar of the voice felix
felixmale
Avatar of the voice milo
milomale
Avatar of the voice atlas
atlasmale
Avatar of the voice orion
orionmale

23 languages

Any voice speaks any of these languages.

Sources and further reading

  1. Wikipedia
  2. TRON developer hub: TRC-20
  3. Creative Commons Attribution 4.0
  4. openai-python on GitHub
  5. ISO 639 language codes
  6. IETF RFC 7845: Ogg Opus
  7. MDN: Web Speech API
  8. OpenAI API reference: create speech
  9. LibriTTS-R corpus (OpenSLR 141)
  10. curl documentation
  11. Python documentation
  12. LibriVox public-domain audiobooks

More on this site