sdmswitch/switch/scripts/demo/asr.lua
2023-10-11 04:39:21 +00:00

106 lines
3.7 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

--[[
要使脚本正确运行,需要安装这些包:
luarocks install xml2lua
]]
--[[
向终端说“再来”,然后再等待终端发来声音
@param s 传的是当前会话session
]]
function again(s)
s:speak("再来")
s:execute("detect_speech", "unimrcp:aliyun aliyun hello")
s:streamFile("silence_stream://-1");
end
--[[
session:setInputCallback的回调函数
@param s session
@param type 由FreeSWITCH传递的input-type可能是dtmf,event等
@param obj 发生input的消息包包括消息头和消息体
@param arg 自定义的参数
]]
function onInput(s, type, obj, arg)
-- 终端触发了dtmf按了按键
if (type == "dtmf") then
s:speak("你按到了" .. obj.digit .. "\n")
again(s)
end
-- 发生终端输入事件
if (type == "event") then
local event = obj:getHeader("Speech-Type")
-- 触发了begin-speaking事件也就是发现终端开始说话了
if (event == "begin-speaking") then
-- log.debug("\n" .. obj:serialize())
return ""
end
-- 触发了detected-speech事件也就是发现终端说话结束了
if (event == "detected-speech") then
s:execute("detect_speech", "pause")
local speech_output = obj:getBody() -- 取到事件的消息体也就是xml类型的语音识别结果
if (speech_output) then
results = getResults(speech_output)
if (results.result ~= nil) then
if (results.result == "你瞅啥?") then
s:speak("瞅你咋地" .. "\n") -- 把识别结果再说给终端
else
s:speak("" .. results.result .. "\n") -- 把识别结果再说给终端
end
else
s:speak("对不起,我没听清你说什么了")
end
again(s) -- 继续下一轮游戏
end
return "break"
else
s:speak("对不起,我没听见你说什么")
return "break"
end
return "break"
end
return "break"
end
--[[
把mrcp传来的xml识别结果解析成lua的table类型
@param asrXml mrcp的语音识别结果
]]
function getResults(asrXml)
local xml2lua = require('xml2lua')
local handler = require('xmlhandler.tree')
local xmlHandler = handler:new()
local xmlParser = xml2lua.parser(xmlHandler)
xmlParser:parse(asrXml)
xml2lua.printable(xmlHandler.root)
--[[
<?xml version="1.0" encoding="utf-8"?><result>
<interpretation grammar="session:hello" confidence="1">
<instance>
<result>乘风破浪。</result>
<beginTime>160</beginTime>
<endTime>1660</endTime>
<taskId>0a07801cb19c48ad9ebe75e001b00e07</taskId>
<waveformUri>dc834b5c7039441f-1.wav</waveformUri>
</instance>
<input mode="speech">乘风破浪。</input>
</interpretation>
</result>
]]
if (xmlHandler.root ~= nil) then
local rec_result = xmlHandler.root.result.interpretation.instance
return rec_result
else
return nil
end
end
-- 脚本实际上从这里开始
session:execute("ring_ready", "1000")
session:execute("playback", "tone_stream://%(1850,4150,475,425);loops=1")
session:answer()
session:setInputCallback('onInput', '')
session:set_tts_params("unimrcp:aliyun", "zhibei_emo")
session:speak("嗨~我们玩个游戏吧,你说什么我就说什么,现在开始!")
session:execute("detect_speech", "unimrcp:aliyun aliyun hello")
session:streamFile("silence_stream://-1");