ImportError:无法从“ google.cloud”(未知位置)导入名称“ texttospeech”

时间:2020-07-24 02:06:36

标签: python

尝试扩展我的discord机器人,该机器人将用户文本的输入转换为音频文件,以便我的机器人可以播放该音频。我只是不知道为什么我不能导入 google 模块。

from google.cloud import texttospeech


def synthesize_text(text):

    """Synthesizes speech from the input string of text."""

    client = texttospeech.TextToSpeechClient()

    input_text = texttospeech.SynthesisInput(text=text)

    # Note: the voice can also be specified by name.
    # Names of voices can be retrieved with client.list_voices().

    voice = texttospeech.VoiceSelectionParams(

        language_code="en-US",
        name="en-US-Standard-C",
        ssml_gender=texttospeech.SsmlVoiceGender.FEMALE,
    )

    audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)

    response = client.synthesize_speech(request={"input": input_text, "voice": voice, "audio_config": audio_config})

    # The response's audio_content is binary.

    with open("output.mp3", "wb") as out:


        out.write(response.audio_content)

        print('Audio content written to file "output.mp3"')

2 个答案:

答案 0 :(得分:1)

如上面的评论所述,您需要先在计算机上安装该库,然后才能在应用程序中调用该函数。

pip install google-cloud-texttospeech

Read through official documentation on usage if required.

根据您的代码,我相信您还勾选了以下项目。

要使用此库,您首先需要完成以下步骤:

  1. 选择或创建一个Cloud Platform项目。
  2. 为您的项目启用结算。
  3. 启用Cloud Text-to-Speech API。
  4. 设置身份验证。

答案 1 :(得分:0)

这对我有用:

pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib

pip install google-cloud-texttospeech