Step By Step
1.获取您的真实AK信息
2.开通智能语音交互服务
3.创建智能语音交互项目
关于创建项目介绍可参考之前的博客:一句话识别
4,依次添加依赖
python -m pip install -r requirements.txt
python -m pip install
import nls
上述命令均需要在SDK根目录中执行
5.通过PythonSDK调用服务
import time
import threading
import sys
import nls
URL = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1"
AKID = ""
AKKEY = ""
APPKEY = ""
# 以下代码会根据音频文件内容反复进行一句话识别
class TestSr:
def __init__(self, tid, test_file):
self.__th = threading.Thread(target=self.__test_run)
self.__id = tid
self.__test_file = test_file
def loadfile(self, filename):
with open(filename, "rb") as f:
self.__data = f.read()
def start(self):
self.loadfile(self.__test_file)
self.__th.start()
def test_on_start(self, message, *args):
print("test_on_start:{}".format(message))
def test_on_error(self, message, *args):
print("on_error args=>{}".format(args))
def test_on_close(self, *args):
print("on_close: args=>{}".format(args))
def test_on_result_chg(self, message, *args):
print("test_on_chg:{}".format(message))
def test_on_completed(self, message, *args):
print("on_completed:args=>{} message=>{}".format(args, message))
def __test_run(self):
print("thread:{} start..".format(self.__id))
sr = nls.NlsSpeechRecognizer(
url=URL,
akid=AKID,
aksecret=AKKEY,
appkey=APPKEY,
on_start=self.test_on_start,
on_result_changed=self.test_on_result_chg,
on_completed=self.test_on_completed,
on_error=self.test_on_error,
on_close=self.test_on_close,
callback_args=[self.__id]
)
while True:
print("{}: session start".format(self.__id))
r = sr.start(aformat="pcm", ex={"hello": 123})
self.__slices = zip(*(iter(self.__data),) * 640)
for i in self.__slices:
sr.send_audio(bytes(i))
time.sleep(0.01)
r = sr.stop()
print("{}: sr stopped:{}".format(self.__id, r))
time.sleep(1)
def multiruntest(num=500):
for i in range(0, num):
name = "thread" + str(i)
t = TestSr(name, "D:\\aa.wav")
t.start()
# 设置打开日志输出
nls.enableTrace(True)
multiruntest(1)
6.运行结果
on_completed:args=>('thread0',) message=>{"header":{"namespace":"SpeechRecognizer","name":"RecognitionCompleted","status":20000000,"message_id":"c4d885d82fe94a4a8baf111e5d4c72f9","task_id":"d7f86b08bcd9417090d1cf8585ea027a","status_text":"Gateway:SUCCESS:Success."},"payload":{"result":"北京的天气","duration":3320}}
thread0: sr stopped:True
on_close: args=>('thread0',)
####参考链接
一句话识别