1#!/usr/bin/env python 2# -*- encoding: utf-8 -*- 3''' 4@File : haas_speech.py 5@Description: file description 6@Date : 2021/04/19 13:56:50 7@Author : 8@version : 1.0 9''' 10import iot 11import utime 12import http 13import ujson as json 14from speech_utils import * 15# from const import * 16 17# 语音播放相关的音频资源文件定义 18resDir = "/data/python-apps/speech/resource/" 19tonepathConnected = "fs:/data/python-apps/speech/resource/connected.wav" 20tonepathPowerOn = "fs:/data/python-apps/speech/resource/poweron.wav" 21 22# 物联网平台相关的key和serect定义 23productSecret = "XXXXXX" 24productKey = "XXXXXX" 25deviceName = "XXXXXX" 26deviceSecret = "XXXXXX" 27 28on_request = False 29on_play = False 30 31def do_connect_lk(): 32 """ 33 @description : 通过物联网平台连接千里传音服务 34 --------- 35 @param : 空 36 ------- 37 @Returns : 空 38 ------- 39 """ 40 # 请替换物联网平台申请到的产品和设备信息,可以参考文章:https://blog.csdn.net/HaaSTech/article/details/114360517 41 global productSecret, productKey, deviceName, deviceSecret ,on_request, on_play 42 # 初始化linkkit sdk 43 key_info = { 44 'region' : 'cn-shanghai' , 45 'productKey': productKey , 46 'deviceName': deviceName , 47 'deviceSecret': deviceSecret , 48 'productSecret': productSecret 49 } 50 device = iot.Device(key_info) 51 # 物联网平台连接成功的回调函数 52 def on_connect(): 53 global player, tonepathConnected 54 print('linkkit is connected ') 55 play(tonepathConnected) 56 device.on('connect',on_connect) 57 # 设置service 事件接收函数(本案例是千里传音) 58 def on_service(data): 59 global on_request, on_play 60 import json 61 print('****** on service ********') 62 print(data) 63 print(data['id']) 64 print(data['param']) 65 serviceid = data['id'] 66 data = json.loads(data['param']) 67 if serviceid == "SpeechPost": 68 on_request = data 69 elif serviceid == "SpeechBroadcast": 70 on_play = data 71 else: 72 pass 73 device.on('service',on_service) 74 # 连接物联网平台 75 device.connect() 76 # 触发linkit sdk持续处理server端信息 77 while(True): 78 device.do_yield(1000) 79 if on_request: 80 download_resource_file(on_request,resDir) 81 on_request = False 82 elif on_play: 83 play_voice(on_play,resDir) 84 on_play = False 85 # 断开连接 86 device.close() 87 player.stop() 88 player.release() 89 90 91 92if __name__ == '__main__': 93 init_audio() 94 play(tonepathPowerOn) 95 do_connect_lk()