1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | class WsParam(object): # 初始化 def __init__(self, APPId, APIKey, APISecret, AudioFile): self.APPId = APPId self.APIKey = APIKey self.APISecret = APISecret self.AudioFile = AudioFile
# 公共参数(common) self.CommonArgs = { 'app_id': self.APPId } # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = { 'domain': 'iat', 'language': 'zh_cn', 'accent': 'mandarin', 'vinfo': 1, 'vad_eos': 10000, 'dwa': 'wpgs', 'ptt': 0 }
# 生成url def create_url(self): url = 'wss://ws-api.xfyun.cn/v2/iat' # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple()))
# 拼接字符串 signature_origin = 'host: ' + 'ws-api.xfyun.cn' + '\n' signature_origin += 'date: ' + date + '\n' signature_origin += 'GET ' + '/v2/iat ' + 'HTTP/1.1' # 进行hmac-sha256进行加密 signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
authorization_origin = 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' % ( self.APIKey, 'hmac-sha256', 'host date request-line', signature_sha) authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8') # 将请求的鉴权参数组合为字典 v = { 'authorization': authorization, 'date': date, 'host': 'ws-api.xfyun.cn' } # 拼接鉴权参数,生成url url = url + '?' + urlencode(v) # print('date: ',date) # print('v: ',v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url |