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

通过Twilio双向媒体流传输Google TTS音频遇杂音问题求助

Twilio双向媒体流WebSocket回传Google TTS音频仅出现杂音问题

我已搭建好Twilio双向媒体流WebSocket,尝试通过Google TTS生成音频并回传给Twilio,但仅能听到短促的尖锐杂音/静电噪音,Google TTS生成的音频本身是正常的。

所用代码

async def send_audio(text):
        client = texttospeech.TextToSpeechClient()

        synthesis_input = texttospeech.SynthesisInput(text=text)

        voice = texttospeech.VoiceSelectionParams(
            language_code="en-IN",
            name="en-IN-Standard-C",
            ssml_gender=texttospeech.SsmlVoiceGender.MALE,
        )
        
        audio_config = texttospeech.AudioConfig(
            audio_encoding=texttospeech.AudioEncoding.MULAW,
            sample_rate_hertz=8000,
            # speaking_rate=1.2
        )

        response = client.synthesize_speech(
            input=synthesis_input, voice=voice, audio_config=audio_config
        )
        # print(response)
        for x in range(0,64):
            audio_content = response.audio_content 
            decoded_audio = base64.b64decode(audio_content)
            trimmed_audio = decoded_audio[x:]
            re_encoded_audio = base64.b64encode(trimmed_audio).decode('utf-8')
            # print(re_encoded_audio)
            print(x)

            outbound_media_meta = {
                "payload": re_encoded_audio,
            }

            outbound_media = {
                "event": "media",
                "media": outbound_media_meta,
                "streamSid": session_stream_sid[call_sid]
            }
            json_message = json.dumps(outbound_media)
            await websocket.send_text(json_message)

尝试的操作

我在发送数据的代码外添加了循环,尝试修剪音频的前0到64字节(参考相关讨论,Google TTS会添加需移除的头部,资料中提到的头部长度有44字节、58字节两种说法)。消息已成功发送至WebSocket,但问题依旧。

针对常见疑问的确认

  • 已确认符合Twilio要求的audio/x-mulaw编码、8000Hz采样率:向Google发起TTS请求时已指定该格式,将返回的base64解码后保存到本地,通过ffprobe和soxi验证,确实是mulaw编码、8000Hz采样率。
  • 已确认仅发送无WAV头部的原始音频:获取Google返回结果后,先解码base64,截取前44字节(WAV头部大小),仅对剩余字节进行base64编码后发送至Twilio。截取后的字节保存到本地,导入Audacity作为mulaw、8000Hz原始音频可正常播放。
  • mulaw/8000字节的base64编码正确:将发送给Twilio的base64字符串保存到test.enc文件,执行base64 test.enc -d > unk.dat后,导入Audacity作为mulaw/8000原始音频可正常播放。已尝试standard、standard-no-pad、url-safe、url-safe-no-pad等多种base64编码方式,均无改善。
  • 发送给Twilio的Media消息格式与官方示例一致,格式正确。
  • 发送的是WS Text消息,符合要求。
  • 已尝试在Media消息后发送Mark消息,问题仍未解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:55:55