skip to Main Content

I’m creating a speech app that transcribes mic input—so far, I’m using rev.ai to transcribe the speech and I’m saving it into the speecharray array. How can I then export the speech to my App.js file so I can display the transcript on my website?

Here’s my file structure:
file structure

Here’s my code for server.js:

const mic = require('mic');
const readline = require('readline');


const token = 'TOKEN';

// initialize client with audio configuration and access token
const audioConfig = new revai.AudioConfig(
    /* contentType */ "audio/x-raw",
    /* layout */      "interleaved",
    /* sample rate */ 16000,
    /* format */      "S16LE",
    /* channels */    1
);

// initialize microphone configuration
// note: microphone device id differs
// from system to system and can be obtained with
// arecord --list-devices and arecord --list-pcms
const micConfig = {
    /* sample rate */ rate: 16000,
    /* channels */    channels: 1,
    /* device id */   device: 'hw:0,0'
};

//KEYBOARD INPUT CODE
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

var client = new revai.RevAiStreamingClient(token, audioConfig);

var micInstance = mic(micConfig);

// create microphone stream
var micStream = micInstance.getAudioStream();

// create event responses
client.on('close', (code, reason) => {
    console.log(`Connection closed, ${code}: ${reason}`);
});
client.on('httpResponse', code => {
    console.log(`Streaming client received http response with code: ${code}`);
});
client.on('connectFailed', error => {
    console.log(`Connection failed with error: ${error}`);
});
client.on('connect', connectionMessage => {
    console.log(`Connected with message: ${connectionMessage}`);
});
micStream.on('error', error => {
  console.log(`Microphone input stream error: ${error}`);
});

// begin streaming session
var stream = client.start();

const speecharray = [];

// create event responses
stream.on('data', data => {
    if (data.type == 'final')
        for (i in data.elements)
            speecharray.push(data.elements[i].value.toLowerCase());

            // umCount = speecharray.filter(value => value == "um");
            // console.log("um count:" + umCount.length);

            // uhCount = speecharray.filter(value => value == "uh");
            // console.log("uh count:" + uhCount.length)

            // score = (umCount.length + uhCount.length) / speecharray.length
            // console.log("score:" + score)


});

// listen for spacebar press to end streaming and display score
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
  if (key.name === 'return') {
    micInstance.stop(); // stop the microphone
    stream.end(); // end the streaming session

    // Calculate and display the score
    const weight = 4;
    const umCount = speecharray.filter(value => value === 'um').length;
    const uhCount = speecharray.filter(value => value === 'uh').length;
    const totalWords = speecharray.length;
    const score = ((umCount*weight + uhCount*weight) / totalWords) * 100;

    console.log(speecharray.join(" "));
    console.log(`Um count: ${umCount}`);
    console.log(`Uh count: ${uhCount}`);
    console.log(`Total words: ${totalWords}`);
    console.log(score)
    console.log(`Fluency: ${100 - score}%`);

    process.stdin.pause(); // pause stdin to stop listening for keypresses
  }
});



//on certain button press log it

stream.on('end', function () {
  console.log("End of Stream");
});

// pipe the microphone audio to Rev AI client
micStream.pipe(stream);

// start the microphone
micInstance.start();

// Forcibly ends the streaming session
// stream.end();

I tried to use export default and import into the App.js but it had a bunch of polyfill errors, which I don’t know what that is. Thanks!

2

Answers


  1. module.exports.speecharray = [];
    

    Then in your app.js file import it using require:

    const speecharray = require('path to server.js').speecharray
    
    Login or Signup to reply.
  2. without exporting you can use Global State and Reducer to store the speecharray
    Then using Globale state you can access anywhere you want.

    // Import necessary modules
    import React, { useState, useReducer } from 'react';
    
    // Define reducer function
    const reducer = (state, action) => {
      switch (action.type) {
        case 'UPDATE_SPEECH_ARRAY':
          return {
            ...state,
            speecharray: action.payload
          };
        default:
          return state;
      }
    };
    
    // Initial state
    const initialState = {
      speecharray: []
    };
    
    // Create context
    export const GlobalContext = React.createContext();
    
    // Create component
    const YourComponent = () => {
      // Use reducer hook to manage state
      const [state, dispatch] = useReducer(reducer, initialState);
    
      // Define function to update speech array
      const updateSpeechArray = (newArray) => {
        dispatch({ type: 'UPDATE_SPEECH_ARRAY', payload: newArray });
      };
    
      return (
        <GlobalContext.Provider
          value={{
            speecharray: state.speecharray,
            updateSpeechArray
          }}
        >
          {/* Your component JSX here */}
        </GlobalContext.Provider>
      );
    };
    
    // To access speecharray from any component, use useContext hook
    // Example:
    /*
    const YourComponent = () => {
      const { speecharray, updateSpeechArray } = useContext(GlobalContext);
      // Your component logic here
    };
    */
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search