Integrating Vietnamese Speech-to-Text API into Node.js for Web Apps

Learn how to integrate Vietnamese Speech-to-Text APIs into Node.js using WebSocket streaming and REST. Complete code examples and practical guidelines included.

In this article
  1. Why Node.js is Ideal for Speech-to-Text Systems
  2. Preparing the Environment and Installing Libraries
  3. Implementing Real-Time Speech Recognition (Streaming)
  4. Handling File Audio Transcription
  5. Optimizing Performance and Handling Errors
  6. Comparing Streaming and REST Methods
  7. Conclusion

In modern web development, voice interaction is becoming a standard requirement for enhancing user experience. Effectively integrating Speech-to-Text (STT) into a Node.js backend requires a solid understanding of data streaming and network connection management. This guide walks you through the process of implementing a Vietnamese-focused STT API in Node.js, ensuring your application responds instantly and accurately.

Why Node.js is Ideal for Speech-to-Text Systems

Node.js, with its event-driven architecture and non-blocking I/O, is a natural fit for low-latency applications like speech processing. When integrating an STT API, you typically handle two types of data: streaming audio via WebSocket for real-time recognition, and file-based audio via REST API for transcribing recorded files.

Using Node.js allows you to manage thousands of concurrent connections efficiently without excessive memory overhead. Additionally, when working with APIs that support Vietnamese, handling code-switching (mixing Vietnamese and English) is smoother due to JavaScript’s robust Unicode string processing capabilities.

Preparing the Environment and Installing Libraries

Before writing any STT JavaScript code, ensure your environment is ready. You need the latest version of Node.js installed. You will also need the ws library for WebSocket handling and axios or node-fetch for REST requests.

Create a new project directory and initialize your npm package:

mkdir stt-demo && cd stt-demo
npm init -y
npm install ws axios dotenv

For security, create a .env file to store your API key. AIVISION provides easy API key management through its console, allowing you to control access and monitor service usage clearly.

Implementing Real-Time Speech Recognition (Streaming)

This is the most complex yet valuable part of integrating speech recognition. Instead of waiting for the user to finish speaking and sending the entire file, streaming allows you to send small audio chunks to the server and receive results immediately.

Here is an example of STT JavaScript code using WebSocket to connect to a speech-to-text API:

const WebSocket = require('ws');
require('dotenv').config();

const API_KEY = process.env.AIVISION_API_KEY;
const WS_URL = `wss://api.s2speech.com/v1/stt/stream?key=${API_KEY}`;

function startRealTimeSTT() {
  const ws = new WebSocket(WS_URL);

  ws.on('open', () => {
  console.log('Connected to STT server');
  // Simulate receiving audio data from a device (e.g., microphone)
  // In practice, you would receive data from the client via socket.io or WebRTC
  const audioChunk = Buffer.from('dummy_audio_data'); 
  ws.send(JSON.stringify({ type: 'audio', data: audioChunk.toString('base64') }));
  });

  ws.on('message', (data) => {
  const response = JSON.parse(data);
  if (response.type === 'partial') {
  console.log('Partial result:', response.text);
  } else if (response.type === 'final') {
  console.log('Final result:', response.text);
  ws.close();
  }
  });

  ws.on('error', (error) => {
  console.error('WebSocket error:', error);
  });
}

startRealTimeSTT();

The key here is handling partial (interim) and final results. This allows your user interface to update text in real-time as the user speaks, creating a sense of immediate responsiveness.

Handling File Audio Transcription

For scenarios requiring the transcription of long recordings (such as meetings or podcasts), use the REST API. This method is simpler but has higher latency since it processes the entire file.

const axios = require('axios');
const fs = require('fs');
const path = require('path');
require('dotenv').config();

const API_KEY = process.env.AIVISION_API_KEY;
const API_URL = 'https://api.s2speech.com/v1/stt/file';

async function transcribeFile(filePath) {
  try {
  const fileBuffer = fs.readFileSync(filePath);
 
  const formData = new FormData();
  formData.append('file', fileBuffer, path.basename(filePath));
  formData.append('lang', 'vi'); // Vietnamese language

  const response = await axios.post(API_URL, formData, {
  headers: {
  'Authorization': `Bearer ${API_KEY}`,
  'Content-Type': 'multipart/form-data'
  }
  });

  console.log('Transcription result:', response.data.text);
  console.log('Word timestamps:', response.data.words);
  } catch (error) {
  console.error('Transcription error:', error.response?.data || error.message);
  }
}

// transcribeFile('sample_audio.mp3');

AIVISION supports returning timestamps for individual words, which is extremely useful when you need to synchronize subtitles or analyze content at specific points in the audio file.

Optimizing Performance and Handling Errors

When deploying a Node.js STT API in a production environment, keep the following points in mind to ensure stability:

  • WebSocket Connection Management: Implement an automatic reconnection mechanism in case the connection drops unexpectedly.
  • Audio Data Compression: Compress audio data on the client side (e.g., using the Opus codec) before sending it to the server to reduce bandwidth usage.
  • Encoding Error Handling: Ensure that the audio encoding (sample rate, bit depth) matches the API requirements. While AIVISION supports various formats, standardizing input helps improve accuracy.
  • Logging and Monitoring: Log errors for easy debugging. Specifically, check if the API key is correct and if the usage quota is still available.

Comparing Streaming and REST Methods

Criteria WebSocket (Streaming) REST (File)
Latency Low (Real-time) High (Requires full file processing)
Use Case Chatbots, virtual assistants, live dictation Long file transcription, post-processing
Complexity High (State management, chunking) Low (Request/Response)
Input Data Continuous audio stream Complete audio file

Choosing the right method depends on your specific application needs. You can combine both: use streaming for direct interaction and REST for storing history.

Conclusion

Integrating a Vietnamese Speech-to-Text API into Node.js is a crucial step in modernizing your web application. With the JavaScript STT code examples and detailed instructions above, you have the knowledge needed to start implementing speech recognition features. AIVISION provides a robust speech-to-text API platform optimized for Vietnamese, allowing you to focus on business logic rather than model accuracy.

If you are looking for a reliable speech recognition solution, visit Start free to experience the latest features. The AIVISION technical team is always ready to support you via Contact to answer any questions during development. Explore more in-depth articles on our Blog.

Frequently asked questions

Does the Node.js STT API support Vietnamese?

Yes, AIVISION designs its Speech-to-Text model optimized for Vietnamese, supporting English code-switching and providing timestamps for each word.

What do I need to do to start using the AIVISION API?

You simply need to create an account at s2speech.com, retrieve your API key from the console, and integrate it into your Node.js application following the guide in this article.

What is the difference between WebSocket and REST API in STT?

WebSocket is used for real-time recognition (streaming) with low latency, while the REST API is used to transcribe pre-recorded audio files, suitable for batch processing.

Do I need a credit card to try AIVISION?

No, AIVISION provides a free trial for every account, with no credit card or prepayment required.

How can I improve the accuracy of speech recognition?

Ensure good input audio quality, use appropriate encoding, and declare the correct language in the API. AIVISION has been trained on a large Vietnamese dataset to optimize accuracy.

Try AIVISION's Vietnamese speech AI

Speech-to-Text, Text-to-Speech and LLM, free.

Start free → Contact

By

Dr. Giang Vo — CEO, AIVISION

Dr. Giang Vo is the CEO of AIVISION, leading the development of s2speech — speech recognition, AI voices and a large language model for Vietnamese — and working with companies at home and abroad on their deployments.

0981 419 967 · giang.vo@aivgroups.com

#Speech-to-Text API#Node.js#Vietnamese STT#WebSocket#REST API#Real-time Transcription

Related articles