Node.js配置Google Cloud Speech-to-Text V2 streamingRecognize报错求助
问题定位与解决方案
核心错误原因
- 默认识别器不支持流式识别:Speech-to-Text V2的
streamingRecognize接口不允许使用全局区域的默认识别器projects/${projectId}/locations/global/recognizers/_,必须使用你在具体地理区域(如us-central1、asia-east1)创建的自定义识别器。 - 参数名拼写错误:你代码中使用了下划线命名的
streaming_config,但Node.js客户端库要求参数名为驼峰式的streamingConfig,这会导致服务端无法正确解析请求参数,触发资源无效错误。 - 区域不匹配:V2识别器必须绑定具体区域,不能使用
global作为位置参数。
正确实现示例
public async initialize() { // 替换为你实际创建的识别器完整路径 // 注意:区域必须和控制台中创建识别器时选择的一致,比如us-central1/asia-east1等 const recognizerName = `projects/${this.projectId}/locations/us-central1/recognizers/your-custom-recognizer-id`; // 流式识别配置,需与音频格式严格匹配 const streamingConfig = { config: { languageCodes: ["zh-CN"], // 替换为你的目标语言代码 encoding: "LINEAR16", // 音频编码格式(如FLAC/MP3等,需和实际音频一致) sampleRateHertz: 16000, // 音频采样率 }, interimResults: true // 是否返回实时中间识别结果,按需开启 }; // 正确的请求参数结构 const initRequest = { recognizer: recognizerName, streamingConfig: streamingConfig }; const stream = this.client .streamingRecognize() .on("data", (response) => { // 处理识别结果 response.results.forEach(result => { const transcript = result.alternatives[0].transcript; console.log(result.isFinal ? `最终结果: ${transcript}` : `实时结果: ${transcript}`); }); }) .on("error", (err) => { console.error("流式识别错误:", err); }); // 发送初始化请求 stream.write(initRequest); // 后续可通过stream.write({ audioContent: audioBuffer })写入音频数据 }
验证步骤
- 确认识别器路径有效性:调用
getRecognizer接口传入上述路径,验证是否能返回识别器的详细配置信息,确保路径无误。 - 检查音频参数匹配:确保
streamingConfig.config中的encoding、sampleRateHertz与你要传输的音频文件/流的属性完全一致。 - 权限校验:确认服务账号拥有
speech.recognizers.stream权限(通常包含在roles/speech.recognition或roles/speech.admin角色中)。
内容的提问来源于stack exchange,提问作者Qwert
相关产品推荐
相关产品推荐

