Frequently asked questions
What is npm?
npm is the package manager for Node.js, allowing you to easily install libraries like the OpenAI SDK. It simplifies dependency management for your IoT projects, ensuring you have the exact tools needed to send text-to-speech requests from your code. Since our API matches the OpenAI speech endpoint, you can use the OpenAI SDK by simply changing the base URL to our API endpoint.
Why use Node.js for TTS?
Node.js runs efficiently on IoT devices like Raspberry Pi. You can use the standard OpenAI SDK by pointing its base URL to https://api.tk971.info/v1, ensuring simple integration. This approach requires no heavy lifting: just send text and receive audio files. It works seamlessly with our API, letting you add voice to your smart home projects without complex coding.
How do I install npm packages?
Run npm install openai in your project directory. This installs the library needed to interact with our API. Ensure Node.js is installed on your device. You can then import the module in your script to start sending speech requests to the endpoint.
What is an API key?
An API key is a unique token (starting with tts-) that authenticates your requests. You get one active key per account on the /get-api-key/ page. Include it in the Authorization: Bearer header. You can issue a new key anytime, which stops the old one immediately.
How do I store API keys securely?
Store your key in an environment variable or a .env file, not in your source code. Use process.env.API_KEY in Node.js. This prevents accidental exposure if you share your code. Our API requires this key for every request to track your balance and limits.
What is a base URL?
The base URL is the root address for API requests. For us, it is https://api.tk971.info/v1. When using the OpenAI SDK, you set this base_url to point to our service. This allows you to use standard SDK methods while hitting our specific infrastructure.
How do I send a request?
Use a POST request to /v1/audio/speech with a JSON body. Include model (tts-1 or tts-1-hd), input (text up to 4096 chars), voice, and response_format. Authenticate with your Bearer token. The API returns the audio file directly in the response for your IoT device.
How do I handle errors?
Check the HTTP status code and response body for error details. Failed requests are free, so you won’t be charged for errors. Implement logic to catch network issues or invalid parameters. Our API returns clear error messages to help you debug your Node.js integration quickly.
What is retry logic?
Retry logic involves re-sending a request after a failure or timeout. Since requests are processed sequentially, network issues might cause delays. Implement exponential backoff in your Node.js code to handle transient errors. This ensures your IoT device eventually receives the audio without manual intervention.
How do I optimize for IoT?
Keep text under 4096 characters per request. Use mp3 or opus for smaller files. For longer texts, split the input into parts of up to 4096 characters and join the resulting audio files yourself. This approach reduces memory usage on devices like Raspberry Pi. Monitor your rate limits (60 requests/minute) to avoid throttling during peak usage.
What are rate limits?
You are limited to 60 requests per minute per key (10 before the first top-up). If you exceed this limit, requests may be delayed or rejected. Monitor your usage on the dashboard. For high-volume IoT deployments, consider scaling your key usage or batching requests efficiently.
How do I test my code?
Sign in with Google to receive a $0.50 free trial (about 50,000 characters) valid for 7 days. Send small text samples to verify voice selection and format. Check the response body for the audio file to confirm success. This allows you to validate your Node.js script before deploying to your actual IoT hardware.
Can I use this with Raspberry Pi?
Yes, Node.js runs well on Raspberry Pi. Install Node.js and npm, then use our API via the OpenAI SDK with the correct base URL. You can trigger audio playback directly from your script. The lightweight nature of the API fits perfectly with embedded IoT workflows.
How do I scale my solution?
Scale by creating additional accounts, as each account holds one active key. There are no monthly plans, so you only pay for what you use. For high volume, split long texts into chunks of 4096 characters. Monitor your balance and rate limits (60 requests per minute per key) to ensure continuous operation across your IoT network.
Introduction to npm and TTS Integration
npm is the default package manager for Node.js, allowing you to easily install and manage libraries. Our text-to-speech API integrates seamlessly into this ecosystem, letting smart home devices generate audio responses without complex backend infrastructure.
What is npm?
npm (Node Package Manager) simplifies dependency management. It lets you add packages like the official OpenAI SDK with a single command, configuring it to point to our API base URL for instant compatibility.
- Standard tool for Node.js projects
- Manages dependencies automatically
- Supports official OpenAI SDK via base_url change
Why Node.js for TTS
Node.js is ideal for IoT because it handles asynchronous I/O efficiently. This means your smart home hub can send text requests and receive audio files without blocking other device operations, keeping your system responsive.
- Non-blocking I/O for smooth operation
- Perfect for async API calls
- Lightweight for constrained environments
Benefits of API Integration
Using a REST API removes the need for heavy local processing. You simply send text and receive audio files, keeping your device firmware simple and your voice quality high without managing large audio models locally.
- No local model management
- Consistent voice quality
- Simple JSON requests
Setting Up Your Environment
Node.js provides a lightweight runtime perfect for smart home hubs and Raspberry Pi projects. It allows you to quickly prototype voice features without heavy dependencies, keeping your device’s resources free for other sensors and services.
Install Node.js
Download the LTS version from nodejs.org. This ensures compatibility with most IoT boards and home automation software like Home Assistant or Node-RED.
Create a New Project
Open your terminal and run npm init -y. This creates a package.json file to track your dependencies and project settings.
Install Required Packages
Install the OpenAI SDK or axios for HTTP requests. Since our API mirrors the OpenAI speech endpoint, you can reuse familiar libraries to send text and receive audio files efficiently.
- npm install openai
- npm install axios

Configuring the API Key
Your API key is the secure credential that authenticates your Node.js scripts with the IoT Voice Labs engine. It links your code directly to your account balance and usage limits, ensuring only your devices can generate speech. You can retrieve or rotate this key instantly from your dashboard at https://tk971.info/get-api-key/.
The key follows the format tts-... and is required in the Authorization: Bearer header. Since each account holds only one active key, issuing a new one immediately invalidates the old one, so update your scripts promptly if you regenerate it to avoid service interruptions.
Get Your Key
Navigate to the /get-api-key/ page on tk971.info after signing in with Google or your email. The dashboard displays your active key, current balance, and a ready-to-use cURL example. You can issue a new key at any time, which instantly deactivates the previous one.
- Available on the /get-api-key/ dashboard
- Format:
tts-... - One active key per account
Store Securely
Treat your API key like a password. Avoid hardcoding it directly in your source files, especially if you push your project to GitHub or share it publicly. Exposure allows others to use your character credits until you notice and rotate the key.
- Avoid hardcoding in source files
- Rotate immediately if exposed
Environment Variables
The best practice is storing your key in an .env file and loading it via process.env. This keeps sensitive data out of your version control system while allowing your Node.js app to access the credential seamlessly during runtime.
- Use
.envfiles - Load via
process.env - Exclude from Git
Writing Your First Script
Once your environment is ready, you can start building your first Node.js script to generate speech. This simple process lets your IoT device or smart home automation routine fetch audio files directly from the API.
We’ll use the official OpenAI SDK for Node.js, configuring it to point to our base URL. This approach keeps your code clean and leverages familiar tools without needing a custom library.
Import the Library
Begin by installing the openai package via npm. Then, import it into your script to access the speech endpoint.
This library handles the JSON structure and authentication headers, simplifying the integration for your smart home projects.
- npm install openai
- const OpenAI = require('openai');
Set the Base URL
Configure the SDK to use our API endpoint by setting the base_url property. This ensures all requests go to https://api.tk971.info/v1.
Keep your API key secure by storing it in an environment variable rather than hardcoding it in your script.
- base_url: 'https://api.tk971.info/v1'
- apiKey: process.env.TTS_API_KEY
Send the Request
Call the audio.speech method with your desired model, voice, input text, and response format. The API returns an audio file you can save or stream to your device.
Remember that requests are processed sequentially, so long texts may take a few seconds to generate.
- model: 'tts-1'
- input: 'Welcome home!'
- voice: 'nova'
- response_format: 'mp3'
Handling the Response
When your Node.js script sends a request to the TTS API, the response contains binary audio data. The specific format you receive depends on your response_format setting: mp3, wav, opus, flac, or pcm. This data is delivered directly in the HTTP response body, ready for immediate processing by your IoT device or local application.
Receive Audio Data
Ensure your code handles the raw binary stream correctly. Since the API returns audio files directly, you must parse the response body as a buffer rather than JSON. This preserves the integrity of the audio data, whether it is compressed (mp3, opus) or uncompressed (wav, pcm, flac).
Save to File
Write the received buffer to disk using Node’s fs module. Specify the correct file extension matching your chosen format. For IoT projects, storing these files locally allows devices to play audio offline, reducing latency and dependency on continuous internet connectivity for playback.
Play Audio Locally
Once saved, use a local audio player library or system command to play the file. This is ideal for smart home devices that need to announce notifications or status updates. Since each request generates a new file, ensure your storage strategy manages file size and retention appropriately.
Error Handling Best Practices
Robust error handling ensures your smart home devices don’t silently fail when the TTS service is busy. Since requests are processed sequentially and may queue under load, anticipating delays is key to a reliable voice interface.
Try-Catch Blocks
Wrap your fetch or HTTP calls in try-catch blocks to catch network failures or invalid responses immediately. This prevents your Node.js script from crashing when the API returns a 4xx or 5xx error, allowing your device to log the issue and continue its primary tasks.
Logging Errors
Log the specific error code, status, and timestamp to your console or local storage. If a request fails, you know exactly when it happened and why, which helps you distinguish between a temporary network glitch and an invalid API key or rate limit issue.
- Log HTTP status codes (e.g., 429 for rate limits).
- Save error messages to local device storage for later review.
- Include the request payload for debugging context.
Retry Mechanisms
Implement a simple retry logic for transient failures, such as network timeouts or 5xx server errors. Since requests may queue during high load, waiting a few seconds before retrying can help avoid immediate failure. Avoid aggressive retry loops to respect the 60 requests per minute rate limit.
- Retry on 5xx errors with a short delay.
- Back off if 429 Too Many Requests is returned.
- Limit retries to prevent battery drain on IoT devices.
Optimizing for IoT Devices
Optimizing audio output for IoT devices requires balancing file size, network efficiency, and power consumption. By selecting appropriate formats and speeds, you ensure your smart home projects run smoothly without unnecessary resource drain.
Choose the right audio format and speed to minimize data usage and storage needs. This approach keeps your device’s battery life extended while maintaining clear voice feedback for users.
Reduce Data Usage
Use Opus or MP3 formats for efficient compression. These formats significantly reduce bandwidth compared to WAV or FLAC, making them ideal for Wi-Fi connected devices or those with limited data plans.
Selecting smaller file sizes helps avoid network congestion and ensures faster delivery of voice commands to your IoT hardware.
- Opus offers the best balance of quality and size.
- MP3 is widely supported and lightweight.
- AVOID WAV/FLAC for high-volume alerts.
Optimize File Size
Adjust the speed parameter to shorten audio duration. Faster speeds reduce the total character count processed per second, leading to smaller files.
Keep input text concise under 4096 characters to avoid splitting requests, which adds overhead to your IoT device's processing.
Use shorter voice presets like Felix or Nova for quick alerts, minimizing the time your device spends transmitting audio data.
- Speed ranges from 0.25 to 4.0.
- Shorter texts mean fewer API calls.
- Efficient compression saves storage space.
Battery Considerations
Minimize active radio time by reducing audio file sizes. Shorter transmission times help extend battery life for wireless sensors and remote devices.
Prefer local playback over streaming where possible. Downloading compact audio files allows your device to play them offline without continuous network activity.
Schedule voice updates during low-power modes if your device supports it, ensuring minimal impact on overall energy consumption.
- Shorter transmissions save battery.
- Local playback reduces network usage.
- Schedule updates for efficiency.

Testing Your Integration
Testing ensures your smart home devices reliably convert text to speech without runtime surprises. By validating both individual components and end-to-end workflows, you guarantee that voice alerts trigger correctly under various network conditions.
This section focuses on verifying that your Node.js scripts handle API responses accurately and that audio files play correctly on connected IoT hardware.
Unit Tests
Write tests to verify that your code correctly formats the JSON request body, including the model, voice, and input fields. Ensure that character counts are calculated accurately before sending requests to stay within the 4096-character limit.
- Validate JSON structure before API submission
- Check character count logic against the 4096 limit
- Verify environment variable parsing for API keys
Integration Tests
Send actual requests to the API endpoint using your trial credit or small top-up. Verify that the response contains valid audio data in the specified format (mp3, wav, opus, flac, or pcm) and that the file size matches expectations.
- Test response parsing for all supported formats
- Verify audio file integrity and duration
- Confirm rate limit headers are respected
Real-World Scenarios
Simulate actual IoT events, such as a motion sensor triggering a voice alert. Test voice selection for different messages and ensure the audio plays correctly on your target hardware, considering battery usage and network latency.
- Trigger voice alerts from sensor events
- Test voice selection for different message types
- Verify playback on target IoT hardware
Scaling Your Solution
Scaling your IoT voice solution requires managing concurrent audio generation without overwhelming your smart home hub. By batching requests or using simple queues, you ensure that multiple devices can receive voice updates smoothly during busy periods.
Keep an eye on your usage dashboard to track character consumption and request volumes. This helps you anticipate needs and avoid unexpected delays as your project grows from a single prototype to a multi-device deployment.
Handle Multiple Requests
Use async/await patterns to send text-to-speech requests for different rooms or sensors simultaneously. This prevents your Node.js script from blocking while waiting for audio files, keeping your smart home interface responsive.
Manage Rate Limits
Your key allows 60 requests per minute. If you trigger multiple devices at once, implement a simple queue to stagger requests slightly. This ensures steady processing without hitting the limit, which is crucial for reliable automated alerts.
Remember that requests are processed sequentially under load, so queuing helps maintain consistent delivery times for your voice commands.
- Limit: 60 requests per minute per key.
- Implement a queue if triggering many devices at once.
- Requests are processed one after another under load.
Monitor Usage
Check your account dashboard regularly to see characters used and balance remaining. Since pricing is per character, monitoring helps you optimize text length for specific IoT notifications.
Track failed requests, which are free, to ensure your integration logic is robust. Understanding your usage patterns helps you plan for larger deployments without unexpected costs.
Troubleshooting Common Issues
Even with simple npm scripts, network hiccups or credential issues can interrupt your smart home voice features. Understanding common failure points helps you keep devices responsive and audio playback smooth without unnecessary debugging delays.
Focus on verifying connectivity, confirming your API key is active, and managing request timing to ensure reliable audio generation for your IoT projects.
Connection Errors
Ensure your Node.js environment has stable internet access. If your device is on a restricted network, verify that outbound HTTPS requests to api.tk971.info are allowed through your firewall or router settings.
- Check DNS resolution for the API domain.
- Verify port 443 is open for outbound traffic.
- Ensure no local proxy blocks the request.
Invalid Keys
If you receive an authentication error, confirm your key starts with tts- and is active in your account dashboard. Keys are single-use; issuing a new key immediately invalidates the old one, so update your environment variables accordingly.
- Regenerate the key via /get-api-key/.
- Update the
Authorization: Bearerheader. - Check for trailing whitespace in the key string.
Timeout Issues
Short phrases typically take a few seconds to generate. If your script times out, increase the Node.js HTTP client timeout duration. Note that under load, requests may queue behind others, so allow extra buffer time for longer texts.
- Increase timeout threshold in your HTTP client.
- Account for queue delays during peak usage.
- Split large texts to reduce generation time.
Advanced Use Cases
Go beyond static prompts by dynamically selecting voices based on context or user preference. For example, use nova for upbeat smart home status updates or atlas for neutral news briefings. This adds personality to your IoT devices without extra coding complexity.
Leverage multi-language support to serve global users. The API handles 23 languages, so you can specify a language code or let the system guess from the text script. This ensures clear audio for devices used in diverse households.
Dynamic Voice Selection
Change voices programmatically to match content tone. Use nova for energetic announcements or sage for calm instructions.
The voice parameter accepts any of the eight presets, allowing real-time customization per request.
- Use
novafor upbeat reminders - Use
sagefor calm instructions - Switch voices via API parameter
Multi-Language Support
Support 23 languages including English, Spanish, German, and Japanese. Set the language field for Latin-script texts to ensure correct pronunciation.
If omitted, the system guesses the language, defaulting to English for Latin text. Explicitly setting it improves accuracy for non-English inputs.
- Supports 23 languages
- Explicit
languagecode recommended - Automatic guessing defaults to English
Automated Alerts
Trigger voice alerts for sensor events like motion detection or temperature changes. Send text via API and play the resulting audio file on connected speakers.
Use mp3 or opus formats to reduce data usage on constrained IoT networks while maintaining quality.
- Trigger alerts via API
- Use
mp3oropusfor efficiency - Integrate with sensor events

Resources and Further Reading
Our documentation covers all technical details for integration, including endpoint specifications, voice parameters, and usage examples.
For direct assistance, please use our contact page to reach the support team via email, as we do not host a dedicated forum or offer live chat.
API Documentation
The full API reference is available at /docs/. It details every endpoint, including the speech generation endpoint and the voice listing endpoint.
You will find ready-to-use code snippets for Node.js, showing how to set the base URL and handle responses.
- Complete endpoint specifications
- Request and response schemas
- Code examples for Node.js
Community Forums
We do not host a dedicated forum. For questions or support, please visit our contact page to send us an email directly.
This ensures your queries are handled by our support team without the noise of a public thread.
Example Projects
Check /get-api-key/ for a ready-made cURL example to test your key immediately.
You can also explore our documentation for additional Node.js integration patterns and voice selection tips.
- cURL examples
- Voice selection tips
- Integration patterns
Listen to the 8 voices
Each sample below was generated by this API from the same sentence. Your devices work together to create a simple, comfortable home without any complex setup or coding knowledge required by you.
23 languages
Any voice speaks any of these languages.
