阿里云语音合成API鉴权与语音合成实现

使用 python版本:

➜   python3 -V
Python 3.6.4

Source code:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import hashlib
import requests
import hmac
import base64
import datetime
import tempfile
class Alibaba:

    def __init__(self):
        
        self.__ak_id = "" # 替换个人用户 id
        self.__ak_secret = "" # 替换个人用户 secret

    def __current_gmt_time(self):

        date = datetime.datetime.strftime(datetime.datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")
        return date

    def __md5_base64(self, body):

        hash = hashlib.md5()
        hash.update(body)
        str_hex = hash.digest()            
        return base64.b64encode(str_hex)

    def __sha1_base64(self, str_to_sign, secret):
        
        hmacsha1 = hmac.new(secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha1)
        return base64.b64encode(hmacsha1.digest()).decode('utf-8')

    def send_request(self,phrase):

        options = { 'method':'POST',
                    'url':'http://nlsapi.aliyun.com/speak?encode_type=mp3&voice_name=xiaoyun&volume=50',
                    'body':phrase.encode('utf-8')
                    }
        headers = {
                    'Authorization':'',
                    'Content-type':'text/plain',
                    'Accept':'audio/mp3,application/json',
                    'Date':self.__current_gmt_time()
                }
        bodyMd5 = self.__md5_base64(options['body']).decode('utf-8')

        feature = options['method']+'\n'+headers['Accept']+'\n'+bodyMd5+'\n'\
                                    +headers['Content-type']+'\n'+headers['Date']
        signature = self.__sha1_base64(feature,self.__ak_secret)
              
        headers['Authorization'] = "Dataplus " + self.__ak_id + ":" + signature
       
        req = requests.post(options['url'], data=options['body'], headers=headers)
        #print(req.json())
        with tempfile.NamedTemporaryFile(suffix='.mp3',delete=False) as f:
            f.write(req.content)
            tmpfile = f.name
            return tmpfile
if __name__=='__main__':

    a = Alibaba()
    a.send_request('今天天气怎么样?') # 输入要合成语音的文字

获得文件:

tmp91s93ebe.mp3

你可能感兴趣的:(阿里云语音合成API鉴权与语音合成实现)