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

Google Cloud Speech Invalid Encoding Error问题排查求助

问题根源及解决方案

核心问题

你遇到的Request message serialization failure: invalid encoding错误,是因为前端传入的Base64字符串包含了data:audio/wav;base64,前缀,而Google Cloud Speech API的audio.content字段要求的是纯Base64编码的音频数据,不能带这个Data URL前缀。

修复步骤

1. 前端处理Base64时移除前缀

修改前端转换Base64的代码,拆分readAsDataURL返回的字符串,只保留纯Base64部分:

this.audioRecordingService.getRecordedBlob().subscribe((data) => {
  this.audioBlob = data.blob;
  this.audioName = data.title;
  var reader = new FileReader();
  reader.readAsDataURL(data.blob);
  reader.onloadend = () => {
    const fullDataUrl = reader.result as string;
    // 拆分字符串,移除Data URL前缀
    this.audioBase64 = fullDataUrl.split(',')[1];
  }
  this.ref.detectChanges();
});

2. 后端添加容错处理(可选但推荐)

为了避免前端处理遗漏,后端可以额外添加前缀校验和自动移除逻辑:

export const transcriptAudio = onCall(async (data) => {
  try {
    let userId = data.auth?.token?.uid;
    if(!userId)
      throw new HttpsError('unauthenticated', 'The user is not authenticated.');

    let audioBase64 = data.data.audioBase64 as string;
    // 容错:如果传入的Base64带Data URL前缀,自动移除
    if (audioBase64.startsWith('data:audio/wav;base64,')) {
      audioBase64 = audioBase64.split(',')[1];
    }

    const client = new SpeechClient();
    const response = await client.recognize(
      {
        audio: {content: audioBase64 },
        config: {
          encoding: "LINEAR16",
          sampleRateHertz: 44100,
          languageCode: "en-US"}});

    const transcription = response[0].results?.map(result => result.alternatives![0].transcript).join('\n');
    // 记得返回转录结果给前端
    return { transcription };
  } catch (error) {
    console.log(`Transcription error: ${error}`);
    // 抛出标准错误让前端捕获
    throw new HttpsError('internal', 'Transcription failed');
  }
});

额外验证要点

  • 前端可以临时添加代码,播放录制的Blob验证音频是否正常:
    const audioUrl = URL.createObjectURL(data.blob);
    const audio = new Audio(audioUrl);
    audio.play();
    
  • 确认RecordRTC的配置正确:你使用的StereoAudioRecorder生成的WAV是PCM编码(对应API要求的LINEAR16),采样率44100也和后端配置一致,这部分没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:52:48