要求Bing文本到语音API时未经授权401

时间:2018-08-20 09:31:52

标签: python text-to-speech bing-api

我正在使用Azure-Samples github中的示例。 https://github.com/Azure-Samples/Cognitive-Speech-TTS/blob/master/Samples-Http/Python/TTSSample.py

我用自己的api密钥替换了,但出现401错误。

这是响应代码和来自API的回复。

401 Unauthorized
Response text:  b''

这是我使用的路径:

token_host = "api.cognitive.microsoft.com"
token_path = "/sts/v1.0/issueToken"
speech_host = "westus.tts.speech.microsoft.com"
speech_path = "/cognitiveservices/v1"

enter image description here

知道发生了什么吗?

2 个答案:

答案 0 :(得分:2)

我遇到了类似的问题,看来正确的API不是

  

https://westus.tts.speech.microsoft.com/cognitiveservices/v1

但是

  

https://speech.platform.bing.com/synthesize

答案 1 :(得分:0)

我遇到了相同的401问题。我切换区域,尝试各种端点均无济于事。

使用以下代码进行操作:

import requests

key = "< YOUR API KEY GOES HERE >"
headers = {
    'Content-type': 'application/x-www-form-urlencoded',
    'Content-Length': '0',
    'Ocp-Apim-Subscription-Key': key,
}

res = requests.post('https://westus.api.cognitive.microsoft.com/sts/v1.0/issuetoken', headers=headers)
print(res.status_code)
token = res.content.decode("utf-8")

fileformat = "audio-16khz-128kbitrate-mono-mp3" 

lang = "en-US"
gender = "Male"
voice = "Microsoft Server Speech Text to Speech Voice (en-US, BenjaminRUS)"
text = "This is a sample text, that Benjamin will speak."

headers = { "Content-type" : "application/ssml+xml",
            "X-Microsoft-OutputFormat" : fileformat,
            "User-Agent" : "TTSForPython",
            "Authorization" : "Bearer " + token, 
            }

body = f"<speak version='1.0' xml:lang='{lang}'><voice xml:lang='{lang}' xml:gender='{gender}' name='{voice}'>{text}</voice></speak>"

res = requests.post('https://westus.tts.speech.microsoft.com/cognitiveservices/v1', headers=headers, data=body)
print(res.status_code)

audiofile = res.content

with open("file.mp3", "wb") as f:
    f.write(audiofile)