使用GCP构建语音转文本遇metadata获取错误,求解决方案
解决GCP语音转文本"Getting metadata from plugin failed"错误
问题描述
使用GCP构建语音转文本功能时,持续触发错误:
Getting metadata from plugin failed with error: key must be a string, a buffer or an object
错误提示该故障并非临时问题,且未主动配置重试逻辑。
现有代码(speech.ts)
import { SpeechClient } from '@google-cloud/speech'; import axios from 'axios'; export async function transcribeAudioFromUrl( audioUrl: string, ): Promise<string> { try { // Configure the Speech-to-Text client with your credentials const speechClient = new SpeechClient({ keyFilename: 'config/client_secret_206787547924-3a46gf902osirh0h7fm5ud7l6e41mtap.apps.googleusercontent.com.json', // Replace with the correct path to your credentials }); // Convert the binary audio data into a buffer const audioBuffer = Buffer.from(audioUrl); console.log({ audioBuffer }); // Perform audio transcription const [responseSpeech] = await speechClient.recognize({ audio: { content: audioBuffer, }, }); const transcription = responseSpeech.results .map((result) => result.alternatives[0].transcript) .join('\n'); return transcription; } catch (error: any) { console.log(error); } }
错误详情
Error: 2 UNKNOWN: Getting metadata from plugin failed with error: key must be a string, a buffer or an object at callErrorFromStatus (/Users/duca/html/sofia/node_modules/@grpc/grpc-js/src/call.ts:81:17) at Object.onReceiveStatus (/Users/duca/html/sofia/node_modules/@grpc/grpc-js/src/client.ts:356:55) at Object.onReceiveStatus (/Users/duca/html/sofia/node_modules/@grpc/grpc-js/src/client-interceptors.ts:454:34) at Object.onReceiveStatus (/Users/duca/html/sofia/node_modules/@grpc/grpc-js/src/client-interceptors.ts:416:48) at /Users/duca/html/sofia/node_modules/@grpc/grpc-js/src/resolving-call.ts:111:24 at processTicksAndRejections (node:internal/process/task_queues:77:11) for call at at ServiceClientImpl.makeUnaryRequest (/Users/duca/html/sofia/node_modules/@grpc/grpc-js/src/client.ts:326:42) at ServiceClientImpl.<anonymous> (/Users/duca/html/sofia/node_modules/@grpc/grpc-js/src/make-client.ts:189:15) at /Users/duca/html/sofia/node_modules/@google-cloud/speech/build/src/v1/speech_client.js:229:29 at /Users/duca/html/sofia/node_modules/google-gax/build/src/normalCalls/timeout.js:44:16 at repeat (/Users/duca/html/sofia/node_modules/google-gax/build/src/normalCalls/retries.js:80:25) at /Users/duca/html/sofia/node_modules/google-gax/build/src/normalCalls/retries.js:118:13 at OngoingCallPromise.call (/Users/duca/html/sofia/node_modules/google-gax/build/src/call.js:67:27) at NormalApiCaller.call (/Users/duca/html/sofia/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js:34:19) at /Users/duca/html/sofia/node_modules/google-gax/build/src/createApiCall.js:84:30 at processTicksAndRejections (node:internal/process/task_queues:95:5) { code: 2, details: 'Getting metadata from plugin failed with error: key must be a string, a buffer or an object', metadata: Metadata { internalRepr: Map(0) {}, options: {} }, note: 'Exception occurred in retry method that was not classified as transient' }
问题分析与修复方案
核心问题
- 凭证类型错误:使用的
client_secret_xxx.json是OAuth客户端凭证,GCP Speech-to-Text需要的是服务账号JSON密钥文件,二者格式不兼容导致身份验证失败。 - 音频处理逻辑错误:直接将音频URL转换为Buffer,实际得到的是URL字符串的二进制编码,而非音频文件的二进制数据。
- 缺少识别配置参数:
recognize请求未指定音频编码、采样率等核心配置,API无法正确解析音频。
修复步骤
1. 替换为正确的服务账号密钥
- 登录GCP控制台,进入「IAM与管理」→「服务账号」
- 创建或选择拥有
Cloud Speech-to-Text Admin权限的服务账号 - 点击「添加密钥」→「创建新密钥」,选择JSON格式下载,替换代码中
keyFilename的路径
2. 修复音频下载逻辑
通过axios下载音频的二进制数据,再转换为Buffer。
3. 添加语音识别配置参数
根据音频实际属性(编码格式、采样率、语言)配置config字段。
修复后完整代码
import { SpeechClient } from '@google-cloud/speech'; import axios from 'axios'; export async function transcribeAudioFromUrl( audioUrl: string, ): Promise<string> { try { // 使用服务账号密钥文件(注意:不是OAuth客户端凭证) const speechClient = new SpeechClient({ keyFilename: 'config/service-account-key.json', // 替换为你的服务账号密钥路径 }); // 下载音频文件的二进制数据 const response = await axios.get(audioUrl, { responseType: 'arraybuffer' }); const audioBuffer = Buffer.from(response.data); // 配置语音识别参数(根据你的音频实际情况调整) const config = { encoding: 'MP3', // 音频编码格式,如MP3、LINEAR16(对应WAV)等 sampleRateHertz: 16000, // 音频采样率 languageCode: 'zh-CN', // 识别语言,如'en-US'、'zh-CN' }; const request = { audio: { content: audioBuffer, }, config: config, }; // 执行语音识别 const [responseSpeech] = await speechClient.recognize(request); const transcription = responseSpeech.results .map((result) => result.alternatives[0].transcript) .join('\n'); return transcription; } catch (error: any) { console.error('转录失败:', error); throw error; // 抛出错误供调用方处理,避免静默失败 } }
额外注意事项
- 确保服务账号拥有
Cloud Speech-to-Text Admin或Cloud Speech-to-Text Editor权限 - 音频参数(编码、采样率)必须与实际音频一致,否则识别会失败或结果不准确
- 检查依赖版本,建议使用最新版的
@google-cloud/speech和axios
内容的提问来源于stack exchange,提问作者Duca
相关产品推荐
相关产品推荐

