微软Azure的TTS接口调用

微软Azure的TTS批处理接口调用

实习让我学会了很多orz

由于要做公司产品和微软产品的对比,故尝试写一个python代码调用微软Azure语音合成API来实现批处理功能。
要实现批处理功能首先得有一个Azure的账号,且要使用标准计费档,免费档是不能使用批处理功能的,它会返回forbidden,拒绝访问。
首先是引入的库。

import subprocess 
import requests
import json
from time import sleep

然后是服务的key,要在微软Azure的平台上获取。把下面的SPEECH_KEY赋值为你的key就行,SPEECH_REGION也要换成相应的服务区域,例如我的就在eastus。

SPEECH_KEY = ""
SPEECH_REGION = "eastus"
text_path=""

get_data函数是我用来获取本地要合成的语音文本的,text_path为输入的文件路径。

def get_data():
    global text_path
    text_path=input()
    with open(text_path,'rb')as f:
        lines=[line[:].decode('utf-8') for line in f]
    data=''.join(lines)
    return data

send_data是post请求发送给Azure。

def send_data():
    url="https://"+SPEECH_REGION+".customvoice.api.speech.microsoft.com/api/texttospeech/3.1-preview1/batchsynthesis"
    data=get_data() #获取要合成文本数据
    headers = {
        "Content-Type": "application/json", # post提交数据的方式
        "Ocp-Apim-Subscription-Key": SPEECH_KEY, 
        "Connection":"Keep-Alive"
    }
    data = {
        "displayName": "batch synthesis sample",
        "description": "my test", 
        "textType": "PlainText", # 负载的数据为纯文本,还可以用SSML格式
        "inputs": [
            {
                "text": data # 待合成的数据文本
            }
        ],
        "properties": {
            "outputFormat": "riff-24khz-16bit-mono-pcm",
            "wordBoundaryEnabled": False,
            "sentenceBoundaryEnabled": False,
            "concatenateResult": True,
            "decompressOutputFiles": False
        },
        "synthesisConfig":{
            "voice": "zh-CN-XiaoxiaoNeural" # 这个是合成的语音音色
        }
    }
    response = requests.post(url, json=data, headers=headers)
    print(response.text) #得到返回信息
    print(response.status_code) #得到返回状态
    synthesis_id=response.json()['id'] #获取此次处理的id,用于后续的查询与语音的获取
    print("synthesis_id",synthesis_id)
    return synthesis_id

request_data是用来查询语音合成的状态的,看看有没有处理完毕。


def request_data(synthesis_id):
    url="https://"+SPEECH_REGION+".customvoice.api.speech.microsoft.com/api/texttospeech/3.1-preview1/batchsynthesis/"+synthesis_id
    #synthesis_id就是刚刚发送请求时得到的此次处理的id
    headers={
        "Ocp-Apim-Subscription-Key": SPEECH_KEY,
        "Connection":"Keep-Alive"
    }
    response = requests.get(url,headers=headers)
    print(response.text)
    print(response.status_code)
    status=response.json()['status'] #得到处理的状态
    while status!="Succeeded": #如果不是succeded,即此次处理为not start或者running,说明还没处理好
        response = requests.get(url,headers=headers) #再次查询
        status=response.json()['status'] #获取状态
        print(response.text)
        print(response.status_code)
        sleep(1) #等待一秒钟
    #print(response.json()['outputs'])
    download_url=response.json()['outputs']['result'] #得到下载语音的网址
    print(download_url)
    return download_url

download_data是下载处理好的语音用的。

def download_data(download_url):
    url=download_url #这是之前得到的网址
    # print(text_path)
    filename=text_path.split(".")
    # print(filename)
    filename=filename[0]+"_result.zip" # 数据名称
    # print(filename)
    response=requests.get(url)
    if response.status_code == 200: #如果获取成功
        with open(filename,'wb') as file:
            file.write(response.content) #把数据保存下来
        print("success")
    else:
        print(response.status_code)

下面是main函数。

def main():
    synthesis_id=send_data() #调用各个函数完成请求的发送查询与数据下载
    download_url=request_data(synthesis_id)
    download_data(download_url)

if __name__ == '__main__':
    main()

最后附上Azure的官方文档,也挺清晰的。→官方文档

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了在Azure中使用TTS(Text-to-Speech)服务的PHP示例代码,你需要进行以下步骤: 1. 首先,确保你已经创建了Azure TTS服务,并获得了相应的密钥。在请求示例中,密钥被称为"密钥一"。 2. 使用cURL库来发送HTTP请求。在示例代码中,首先初始化一个cURL句柄,并设置一些选项,如URL、请求方法、请求头等。 3. 设置请求的URL为"https://eastus.api.cognitive.microsoft.com/sts/v1.0/issueToken",这是用于获取访问令牌的端点。 4. 设置请求方法为POST,并添加必要的请求头,包括"User-Agent"和"Ocp-Apim-Subscription-Key"。注意将"密钥一"替换为你自己的密钥。 5. 执行cURL请求,获取响应。 6. 关闭cURL句柄。 7. 最后,输出响应。 这个示例代码将向TTS服务发送一个请求,以获取访问令牌。你可以根据需要将其集成到你的PHP应用程序中,并在获取到访问令牌后使用它来进行TTS的相关操作。 请注意,示例代码中的URL和密钥是占位符,你需要根据你自己的Azure TTS服务的配置进行相应的替换。 参考资料: Kudu 仪表盘: [web站点名称].azurewebsites.net,然后 Kudu 仪表盘是 » https:// 自定义编译PHP可以上传自己编译的PHP到D:\Home (C:\不可写)。然后在Azure门户,为.php的SCRIPT_PROCESSOR设置为自己编译的php-cgi.exe文件的绝对路径。 PHP请求示例: ```php <?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://eastus.api.cognitive.microsoft.com/sts/v1.0/issueToken', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74', 'Ocp-Apim-Subscription-Key: 密钥一' ), )); $response = curl_exec($curl); curl_close($curl); echo $response; ?> ``` 希望这个回答能够帮助到你!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [在Azure 应用服务安装 PHP](https://blog.csdn.net/it_xiangqiang/article/details/127076780)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [Azure text-to-speech 语音合成 中文晓晓情感API使用及教程](https://blog.csdn.net/qq_42945182/article/details/115291886)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值