|

|  How to Use IBM Watson Speech to Text API in Node.js

How to Use IBM Watson Speech to Text API in Node.js

October 31, 2024

Master IBM Watson Speech to Text API integration in Node.js with our expert guide. Enhance your applications with seamless voice recognition functionality.

How to Use IBM Watson Speech to Text API in Node.js

 

Setting Up the Node.js Environment

 

  • Ensure you have Node.js and npm installed on your machine. You can verify this by running node -v and npm -v in the terminal to check their versions.
  •  

  • Create a new directory for your project and navigate into it. For instance, use mkdir watson-stt && cd watson-stt.
  •  

  • Initialize a new Node.js project by executing npm init -y. This creates a package.json file with default settings.

 

Installing IBM Watson SDK

 

  • Install the IBM Watson SDK for Node.js by executing the following command in your terminal:

    ```shell
    npm install ibm-watson@latest
    ```

  •  

  • Additionally, you need to install the axios library for making HTTP requests:

    ```shell
    npm install axios
    ```

 

Authentication and Configuration

 

  • Generate an API key and URL from the IBM Cloud dashboard for the Speech to Text service. Take note of these credentials as you will use them in your application.
  •  

  • Create a config file named .env to store your API key and URL. Make sure that your .gitignore file is set to exclude the .env file to keep your credentials secure. Inside .env, insert:

    ```plaintext
    API_KEY=your-ibm-watson-api-key
    API_URL=your-ibm-watson-url
    ```

 

Building the Node.js Application

 

  • Create a new JavaScript file, say app.js, within your project directory.
  •  

  • In your app.js, require the necessary modules and configure the IBM Watson Speech to Text service:

    ```javascript
    require('dotenv').config();
    const fs = require('fs');
    const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
    const { IamAuthenticator } = require('ibm-watson/auth');

    const speechToText = new SpeechToTextV1({
    authenticator: new IamAuthenticator({
    apikey: process.env.API_KEY,
    }),
    serviceUrl: process.env.API_URL,
    });
    ```

 

Converting Audio to Text

 

  • Prepare an audio file for testing and place it in your project directory. Ensure it is in a supported format such as WAV, FLAC, or MP3.
  •  

  • Add the following code to handle the conversion from speech to text:

    ```javascript
    const transcribeAudio = async (audioFilePath) => {
    const params = {
    audio: fs.createReadStream(audioFilePath),
    contentType: 'audio/wav', // Change content-type as per your audio file format
    };

    try {
      const response = await speechToText.recognize(params);
      const transcription = response.result.results
        .map(result => result.alternatives[0].transcript)
        .join('\n');
      console.log('Transcription:', transcription);
    } catch (error) {
      console.error('Error transcribing audio:', error);
    }
    

    };

    // Transcribe a sample audio file
    transcribeAudio('sample-audio.wav');
    ```

 

Run Your Application

 

  • Run your application by using the command node app.js from your terminal. Observe the console for the transcription output of your audio file.
  •  

  • Verify the transcription and adjust the content type if necessary by checking the format of your audio files.