Integrating Speech-to-Text API in Node.js: A Practical Guide for Web Apps
Learn how to integrate Speech-to-Text APIs in Node.js using REST and WebSocket. A practical guide with code examples for real-time and file transcription.
In this article
Converting voice to text is a critical feature for enhancing user experience in modern applications. To deploy this effectively, mastering the integration of Speech-to-Text APIs in Node.js is a foundational step. This article provides a practical walkthrough, from environment setup to handling web audio data, helping you build a stable and accurate speech recognition system.
Why Integrate STT APIs into Node.js Systems?
Node.js, with its single-threaded, non-blocking I/O architecture, is an ideal choice for applications handling numerous simultaneous connections. When combined with speech recognition services, you can create features like quick note-taking, virtual assistants, or meeting-to-text conversion.
Instead of building and training expensive AI models from scratch, using APIs from specialized providers like AIVISION saves development time and ensures high accuracy for Vietnamese. AIVISION focuses on speech AI for the Vietnamese language, supporting both English and Vietnamese within the same sentence (code-switching), which aligns well with real-world usage in the Vietnamese market.
Preparing the Development Environment
Before you begin, ensure you have the following components ready:
- Node.js: Version 16 or higher to support modern APIs.
- npm: The package manager.
- API Key: Create an account and obtain your API key from the service provider's console.
- WebSocket Library: For handling real-time streaming connections.
You can initialize your project with npm init -y and install the necessary libraries. For audio processing in the browser, you will need to use the Web Audio API or MediaRecorder API to capture audio data before sending it to the server.
Handling Web Audio and Sending Data
There are two primary methods for sending audio data to a Node.js server:
1. Sending Audio Files (REST API)
This approach is suitable when the user has finished recording and wants to receive the results afterward.
Step 1: Record Audio in the Browser
Use the MediaRecorder API to record audio and create a Blob.
let mediaRecorder;
let chunks = [];
function startRecording() {
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = e => chunks.push(e.data);
mediaRecorder.start();
});
}
function stopRecording() {
mediaRecorder.stop();
mediaRecorder.onstop = () => {
const blob = new Blob(chunks, { type: 'audio/webm' });
sendToServer(blob);
};
}
Step 2: Upload File to Node.js
Use the multer library in Express.js to handle file uploads.
const express = require('express');
const multer = require('multer');
const axios = require('axios');
const app = express();
const upload = multer({ dest: 'uploads/' });
app.post('/transcribe', upload.single('audio'), async (req, res) => {
try {
const fileStream = fs.createReadStream(req.file.path);
// Call STT API via REST
const response = await axios.post('https://api.s2speech.com/v1/transcriptions', {
file: fileStream,
language: 'vi'
}, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'multipart/form-data'
}
});
res.json(response.data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
2. Real-Time Streaming (WebSocket)
This method is preferred for applications requiring immediate feedback, such as live captions or voice assistants.
Step 1: Establish WebSocket Connection from Client
const ws = new WebSocket('wss://api.s2speech.com/v1/stream');
ws.onopen = () => {
console.log('Connected to STT server');
// Send audio chunks when new data is available
mediaRecorder.ondataavailable = (e) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(e.data);
}
};
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Transcript:', data.text);
};
Step 2: Proxy WebSocket via Node.js
Node.js acts as a middle layer to protect your API key and handle business logic.
const WebSocket = require('ws');
const http = require('http');
const server = http.createServer();
const wss = new WebSocket.Server({ server });
wss.on('connection', (clientWs) => {
const serverWs = new WebSocket('wss://api.s2speech.com/v1/stream');
serverWs.on('open', () => {
clientWs.send(JSON.stringify({ status: 'connected' }));
});
clientWs.on('message', (data) => {
serverWs.send(data);
});
serverWs.on('message', (data) => {
clientWs.send(data);
});
});
Optimizing Performance and Accuracy
To ensure your Node.js speech recognition system runs smoothly, keep the following technical points in mind:
- Compress Audio Data: Before sending to the server, compress audio into suitable formats (like WebM or OGG) to reduce bandwidth usage.
- Handle Network Errors: Implement retry mechanisms if the WebSocket connection drops.
- Configure Language: Clearly define the input language. AIVISION supports both Vietnamese and English, handling mixed-language scenarios effectively to improve accuracy for Vietnamese users.
- Timestamps: If you need to display text in real-time, request word timestamps from the API to synchronize with the audio.
Comparison of Integration Methods
| Criteria | REST API (File) | WebSocket (Streaming) |
|---|---|---|
| Latency | High (waits for full file processing) | Low (continuous updates) |
| Complexity | Low | Medium |
| Best For | File uploads, post-meeting notes | Live captions, virtual assistants, real-time notes |
| Error Handling | Easier (request/response) | More complex (requires connection state management) |
Tips for Developers
When implementing Speech-to-Text APIs in Node.js, start with the REST method to verify basic functionality. Then, upgrade to WebSocket when you need real-time capabilities. Ensure you test thoroughly on various mobile devices, as microphone quality and audio codecs on phones can differ significantly from desktops.
Additionally, leverage supplementary features like word timestamps to create a more professional user experience, especially in online meeting apps or podcast recordings.
Conclusion
Integrating Speech-to-Text APIs into Node.js systems is a technical process but entirely feasible if you understand audio processing and connection management. Choosing the right API provider with high accuracy for Vietnamese will help your product achieve excellent quality.
AIVISION offers Speech-to-Text and Text-to-Speech solutions focused on Vietnamese, with strong code-switching capabilities and diverse output formats. You can start testing these features today.
Read more technical articles on the Blog
If you need technical support or want to learn more about speech solutions, please Contact our technical team.
Start Free Trial of AIVISION's AI speech services now to experience high accuracy and fast processing.
Frequently asked questions
Does the STT API in Node.js support Vietnamese?
Yes, AIVISION provides a Speech-to-Text API specifically designed for Vietnamese, supporting both English and Vietnamese within the same sentence to ensure high accuracy for Vietnamese users.
How can I record audio directly from a web browser?
You can use the browser's MediaRecorder API to capture audio and create data chunks, then send them to your Node.js server via WebSocket or REST API.
Should I use REST or WebSocket for web audio recording apps?
If you need immediate results (real-time), use WebSocket. If users record first and then submit for results, the REST API is simpler and easier to implement.
What audio formats does AIVISION support?
AIVISION supports many common audio formats and is particularly optimized for streaming via WebSocket and file uploads via REST API.
How do I get an API key to start development?
You can create a free account on AIVISION's signup page to receive an API key and start integrating it into your Node.js project.
Try AIVISION's Vietnamese speech AI
Speech-to-Text, Text-to-Speech and LLM, free.
Start free → Contact