You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将server.js中创建的speecharray数组导出至App.jsx?

问题描述

我正在开发一款语音转写应用,通过rev.ai处理麦克风输入的语音,并将转写内容存入speecharray数组。请问如何将该数组导出到App.js,以在网站上展示转写文本?

文件结构

项目包含server.js、App.js等文件,属于Node.js后端+前端框架的典型结构

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();

我尝试使用export default并导入到App.js中,但出现了大量polyfill错误,不清楚问题出在哪,求解决。


解决方案

你遇到的核心问题是混淆了Node.js后端与前端代码的运行环境:server.js是运行在Node.js环境的后端代码,直接用export default导出给前端App.js,会因为环境差异(比如Node.js核心模块mic、readline在浏览器中不存在)触发大量polyfill错误。

正确的做法是通过前后端通信传递speecharray数据,具体步骤如下:

1. 为后端添加HTTP服务(修改server.js)

用Express快速搭建HTTP服务,提供接口让前端获取转写数据:

// 先安装依赖:npm install express cors
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

// 将speecharray改为全局可访问的变量
let speecharray = [];

// --- 原有代码保持不变,仅替换原const speecharray = []为上面的let声明 ---

// 添加接口返回转写内容和统计数据
app.get('/get-transcript', (req, res) => {
  const umCount = speecharray.filter(v => v === 'um').length;
  const uhCount = speecharray.filter(v => v === 'uh').length;
  const totalWords = speecharray.length;
  const score = ((umCount*4 + uhCount*4) / totalWords) * 100;

  res.json({
    transcript: speecharray.join(' '),
    stats: {
      umCount,
      uhCount,
      totalWords,
      fluency: 100 - score
    }
  });
});

// 启动HTTP服务,端口设为3001
app.listen(3001, () => {
  console.log('后端服务运行在 http://localhost:3001');
});

2. 前端App.js请求数据

在前端通过fetch或axios调用后端接口,获取并展示转写内容:

// 示例用fetch实现
async function loadTranscript() {
  try {
    const response = await fetch('http://localhost:3001/get-transcript');
    const data = await response.json();
    
    // 将内容渲染到页面
    document.getElementById('transcript-content').textContent = data.transcript;
    document.getElementById('fluency-stats').textContent = 
      `Um次数:${data.stats.umCount} | Uh次数:${data.stats.uhCount} | 流利度:${data.stats.fluency.toFixed(2)}%`;
  } catch (err) {
    console.error('获取转写数据失败:', err);
  }
}

// 可以绑定到按钮点击或定时调用,实现内容更新
// 比如页面添加按钮:<button onclick="loadTranscript()">刷新转写内容</button>

3. 实时更新优化(可选)

如果需要实时展示转写内容,可改用WebSocket实现双向通信:

  • 后端用ws模块创建WebSocket服务
  • 前端连接WebSocket,后端在stream.on('data')触发时,主动推送最新转写内容到前端

为什么直接导出不行?

server.js依赖Node.js核心模块和系统级麦克风访问能力,这些在浏览器环境中无法运行。直接导出会让前端打包工具(如Webpack)尝试为这些Node.js模块生成polyfill,从而引发大量错误。


内容的提问来源于stack exchange,提问作者user24171251

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:55:01