Python 无法获取Azure认知服务的访问令牌(用于tts)

Python 无法获取Azure认知服务的访问令牌(用于tts),python,azure,text-to-speech,access-token,microsoft-cognitive,Python,Azure,Text To Speech,Access Token,Microsoft Cognitive,我似乎无法获得Azure认知服务访问令牌的授权。我正在使用azure团队发布到github的示例代码(修改为获取我的密钥) 我已经阅读了文档,据我所知,我做的一切都是对的。我还使用了“免费试用的统一语音服务”,但这也不起作用 class TextToSpeech(对象): 定义初始化(自,订阅密钥): self.subscription\u key=订阅\u key self.tts=“使用python测试Azure的tts功能” #self.tts=input(“您希望将什么转换为语音:”)

我似乎无法获得Azure认知服务访问令牌的授权。我正在使用azure团队发布到github的示例代码(修改为获取我的密钥)

我已经阅读了文档,据我所知,我做的一切都是对的。我还使用了“免费试用的统一语音服务”,但这也不起作用

class TextToSpeech(对象):
定义初始化(自,订阅密钥):
self.subscription\u key=订阅\u key
self.tts=“使用python测试Azure的tts功能”
#self.tts=input(“您希望将什么转换为语音:”)
self.timestr=time.strftime(“%Y%m%d-%H%m”)
self.access\u令牌=无
'''
TTS端点需要访问令牌。此方法交换您的
有效期为十分钟的访问令牌的订阅密钥。
'''
def get_令牌(自身):
获取\u令牌\u url=”https://eastus.api.cognitive.microsoft.com/sts/v1.0/issuetoken"
标题={
“Ocp Apim订阅密钥”:self.Subscription\u密钥
}
response=requests.post(fetch\u token\u url,headers=headers)
self.access\u token=str(response.text)
如果名称=“\uuuuu main\uuuuuuuu”:
app=TextToSpeech(订阅密钥)
app.get_token()
下面是访问令牌的输出

“{”error:{”code:“401”,“message:“由于订阅密钥无效或API终结点错误,访问被拒绝。请确保为活动订阅提供有效密钥,并为您的资源使用正确的区域API终结点。“}”

我应该得到的是临时访问令牌,但由于某种原因,我得到了上述错误,我不知道原因。

此错误是由于您调用了错误的端点。请尝试下面的代码,在main方法中使用您自己的订阅参数:

import os, requests, time
from xml.etree import ElementTree


try: input = raw_input
except NameError: pass



class TextToSpeech(object):
    def __init__(self, subscription_key,region):
        self.subscription_key = subscription_key
        self.region =region
        self.tts = input("What would you like to convert to speech: ")
        self.timestr = time.strftime("%Y%m%d-%H%M")
        self.access_token = None

    def get_token(self):
        fetch_token_url = 'https://'+self.region+'.api.cognitive.microsoft.com/sts/v1.0/issuetoken'
        headers = {
            'Ocp-Apim-Subscription-Key': self.subscription_key
        }
        response = requests.post(fetch_token_url, headers=headers)
        self.access_token = str(response.text)

    def save_audio(self):
        base_url = 'https://'+self.region+'.tts.speech.microsoft.com/'
        path = 'cognitiveservices/v1'
        constructed_url = base_url + path
        headers = {
            'Authorization': 'Bearer ' + self.access_token,
            'Content-Type': 'application/ssml+xml',
            'X-Microsoft-OutputFormat': 'riff-24khz-16bit-mono-pcm',
            'User-Agent': 'YOUR_RESOURCE_NAME'
        }
        xml_body = ElementTree.Element('speak', version='1.0')
        xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
        voice = ElementTree.SubElement(xml_body, 'voice')
        voice.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-US')
        voice.set('name', 'en-US-Guy24kRUS') # Short name for 'Microsoft Server Speech Text to Speech Voice (en-US, Guy24KRUS)'
        voice.text = self.tts
        body = ElementTree.tostring(xml_body)

        response = requests.post(constructed_url, headers=headers, data=body)
        '''
        If a success response is returned, then the binary audio is written
        to file in your working directory. It is prefaced by sample and
        includes the date.
        '''
        if response.status_code == 200:
            with open('sample-' + self.timestr + '.wav', 'wb') as audio:
                audio.write(response.content)
                print("\nStatus code: " + str(response.status_code) + "\nYour TTS is ready for playback.\n")
        else:
            print("\nStatus code: " + str(response.status_code) + "\nSomething went wrong. Check your subscription key and headers.\n")

    def get_voices_list(self):
        base_url = 'https://'+self.region+'.tts.speech.microsoft.com/'
        path = 'cognitiveservices/voices/list'
        constructed_url = base_url + path
        headers = {
            'Authorization': 'Bearer ' + self.access_token,
        }
        response = requests.get(constructed_url, headers=headers)
        if response.status_code == 200:
            print("\nAvailable voices: \n" + response.text)
        else:
            print("\nStatus code: " + str(response.status_code) + "\nSomething went wrong. Check your subscription key and headers.\n")

if __name__ == "__main__":
    region = '<your region here , in your case , the value should be eastus>'
    subscription_key = '<your subscription key here>'
    app = TextToSpeech(subscription_key,region)
    app.get_token()
    app.save_audio()
导入操作系统、请求、时间
从xml.etree导入元素树
try:input=原始输入
除了名称错误:通过
类TextToSpeech(对象):
定义初始化(自我、订阅密钥、区域):
self.subscription\u key=订阅\u key
self.region=区域
self.tts=input(“您希望将什么转换为语音:”)
self.timestr=time.strftime(“%Y%m%d-%H%m”)
self.access\u令牌=无
def get_令牌(自身):
fetch_token_url='https://'+self.region+'.api.cognitive.microsoft.com/sts/v1.0/issuetoken'
标题={
“Ocp Apim订阅密钥”:self.Subscription\u密钥
}
response=requests.post(fetch\u token\u url,headers=headers)
self.access\u token=str(response.text)
def保存_音频(自):
base_url='https://'+self.region+'.tts.speech.microsoft.com/'
路径='cognitiveservices/v1'
构造的url=基本url+路径
标题={
“授权”:“承载人”+自访问令牌,
“内容类型”:“应用程序/ssml+xml”,
“X-Microsoft-OutputFormat”:“riff-24khz-16bit-mono-pcm”,
“用户代理”:“您的资源名”
}
xml_body=ElementTree.Element('speak',version='1.0')
xml_body.set('{http://www.w3.org/XML/1998/namespace}朗格(英语)
voice=ElementTree.SubElement(xml_body,'voice')
语音设置('{http://www.w3.org/XML/1998/namespace}朗格(英语)
voice.set('name','en-US-Guy24kRUS')#Microsoft Server语音文本到语音语音(en-US,Guy24kRUS)的简称
voice.text=self.tts
body=ElementTree.tostring(xml_body)
response=requests.post(构建url,headers=headers,data=body)
'''
如果返回成功响应,则写入二进制音频
在您的工作目录中归档。它以示例和示例开头
包括日期。
'''
如果response.status_code==200:
打开('sample-'+self.timestr+'.wav',wb')作为音频:
音频.写入(响应.内容)
打印(“\n状态代码:“+str(响应状态代码)+”\n您的TTS已准备好播放。\n”)
其他:
打印(“\n状态代码:“+str(响应状态代码)+”\n出现问题。请检查订阅密钥和标题。\n”)
def get_voices_列表(自我):
base_url='https://'+self.region+'.tts.speech.microsoft.com/'
路径='cognitiveservices/voices/list'
构造的url=基本url+路径
标题={
“授权”:“承载人”+自访问令牌,
}
response=requests.get(构造url,headers=headers)
如果response.status_code==200:
打印(“\nAvailable voices:\n”+response.text)
其他:
打印(“\n状态代码:“+str(响应状态代码)+”\n出现问题。请检查订阅密钥和标题。\n”)
如果名称=“\uuuuu main\uuuuuuuu”:
区域=“”
订阅密钥=“”
app=TextToSpeech(订阅密钥,地区)
app.get_token()
app.save_audio()
您可以在Azure portal上的以下位置找到您的地区和订阅密钥值:

我已经在我这边进行了测试,它对我有效。一旦您完成代码,将创建一个wav文件,这就是您需要的:

您的资源位于哪些地区?您是否使用azure门户“快速入门”页面中的端点url和密钥?该地区位于美国东部。在美国西部有一个“尝试30天”,用那个钥匙在那个地区也不起作用。对不起,我就在完成硕士论文的时候,我可能再过一两个星期就不可能了。一旦我有机会弄明白,我一定会让你知道的。