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

使用Pygame播放Google Cloud TTS生成的WAV文件出现尖锐杂音求助

Google Cloud TTS生成音频用Pygame播放出现尖锐高音问题

我正在制作一个采用Google Cloud TTS语音的语音助手,严格跟随YouTube视频步骤操作后,唯独遇到播放时音频尖锐或超高音调的问题。尝试过pyAudio、sounddevice、pydub等其他模块,也调整过音高、频率、采样率等参数,但都无法解决杂音问题。生成的WAV文件本身是24000Hz,播放正常,但通过Pygame处理后就出现异常,希望能得到帮助。

相关代码

def unique_languages_from_voices(voices):
    language_set = set()
    for voice in voices:
        for language_code in voice.language_codes:
            language_set.add(language_code)
    return language_set


def list_languages():
    client = tts.TextToSpeechClient()
    response = client.list_voices()
    languages = unique_languages_from_voices(response.voices)

    print(f" Languages: {len(languages)} ".center(60, "-"))
    for i, language in enumerate(sorted(languages)):
        print(f"{language:>10}", end="\n" if i % 5 == 4 else "")



def list_voices(language_code=None):
    client = tts.TextToSpeechClient()
    response = client.list_voices(language_code=language_code)
    voices = sorted(response.voices, key=lambda voice: voice.name)

    print(f" Voices: {len(voices)} ".center(60, "-"))
    for voice in voices:
        languages = ", ".join(voice.language_codes)
        name = voice.name
        gender = tts.SsmlVoiceGender(voice.ssml_gender).name
        rate = voice.natural_sample_rate_hertz
        print(f"{languages:<8} | {name:<24} | {gender:<8} | {rate:,} Hz")


def text_to_wav(voice_name: str, text: str):
    language_code = "-".join(voice_name.split("-")[:2])
    text_input = tts.SynthesisInput(text=text)
    voice_params = tts.VoiceSelectionParams(
        language_code=language_code, name=voice_name
    )
    audio_config = tts.AudioConfig(audio_encoding=tts.AudioEncoding.LINEAR16)

    client = tts.TextToSpeechClient()
    response = client.synthesize_speech(
        input=text_input, voice=voice_params, audio_config=audio_config
    )


    filename = f"{voice_name}.wav"
    with open(filename, "wb") as out:
        out.write(response.audio_content)
        print(f'Generated speech saved to "{filename}"')

    return response.audio_content

list_languages()
list_voices("en")

generated_speech = text_to_wav('en-US-News-K', 'Make yourself comfortable, Hacker. Stay a while.')
pygame.mixer.init(frequency=24000, buffer = 2048)
speech_sound = pygame.mixer.Sound(generated_speech)
speech_sound.play()
time.sleep(5)
pygame.mixer.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:25:15