Node.js开发:如何获取Twilio TwiML <Gather>语音输入并实现分支播报
Twilio外呼语音识别分支播报完整实现方案
核心运行逻辑
原来的外呼脚本仅负责发起呼叫,本身无法直接接收<Gather>组件采集的语音内容。Twilio的Gather组件会在平台侧完成语音转文字,之后将识别结果通过HTTP请求推送到你为Gather配置的action地址。你只需要在这个地址对应的服务逻辑里,接住识别到的文本做分支判断,返回对应播报内容的TwiML即可。
原有流程的问题修正
你目前配置的TwiML里<Gather>是空标签,既没有指定识别结果的接收地址,也没有给用户输入提示,需要先调整:
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say>Calling Established...</Say> <Pause length="30"/> <Say>Claim Status</Say> <Pause length="10"/> <!-- 关键配置:指定结果接收地址、HTTP方法,加输入引导 --> <Gather input="speech" action="/voice/handleGatherResult" method="POST" speechTimeout="auto" > <Say>Please say Medical for your health ID, or Dental for your dental ID</Say> </Gather> <!-- 用户超时未输入的兜底提示 --> <Say>Sorry we didn't receive your input, please try again later</Say> </Response>
完整Node.js服务实现
因为需要常驻服务接收Twilio的请求,这里用最轻量化的Express框架搭建,新手可以直接复制使用。
- 先安装所有需要的依赖,在项目目录执行:
npm install express twilio body-parser - 完整服务代码(带逐行注释):
// 导入依赖 const express = require('express'); const twilio = require('twilio'); const bodyParser = require('body-parser'); const app = express(); // 配置请求参数解析中间件 app.use(bodyParser.urlencoded({ extended: false })); // 接口1:对应外呼脚本里填的 /voice/callUHC.xml 地址,返回初始呼叫流程 app.get('/voice/callUHC.xml', (req, res) => { const twiml = new twilio.twiml.VoiceResponse(); twiml.say('Calling Established...'); twiml.pause({ length: 30 }); twiml.say('Claim Status'); twiml.pause({ length: 10 }); // 配置Gather采集组件 const gather = twiml.gather({ input: 'speech', action: '/voice/handleGatherResult', method: 'POST', speechTimeout: 'auto' }); gather.say('Please say Medical for your health ID, or Dental for your dental ID'); // 超时未输入的兜底逻辑 twiml.say('Sorry we didn't receive your input, please try again later'); res.type('text/xml'); res.send(twiml.toString()); }); // 接口2:Gather采集结果的接收地址,实现分支播报逻辑 app.post('/voice/handleGatherResult', (req, res) => { // 从Twilio推送的参数里拿语音识别文本,字段名固定为SpeechResult const userInput = (req.body.SpeechResult || '').trim().toLowerCase(); const twiml = new twilio.twiml.VoiceResponse(); // 分支判断 if (userInput.includes('medical')) { twiml.say('Your medical claim ID is 123456789'); } else if (userInput.includes('dental')) { twiml.say('Your dental claim ID is 987654321'); } else { // 识别到无法匹配的内容,引导用户重试 twiml.say('Sorry we didn't understand that input. Please say Medical or Dental'); // 重新跳转回初始采集流程 twiml.redirect('/voice/callUHC.xml'); } res.type('text/xml'); res.send(twiml.toString()); }); // 本地启动服务,端口3000 app.listen(3000, () => { console.log('Voice service running on http://localhost:3000'); });
新手实操注意事项
- 不要对识别结果做严格全等匹配:Twilio的语音识别可能返回带冗余的文本(比如用户说“我要查medical的信息”),用
includes做关键词模糊匹配的兼容性更好 - 本地服务启动后,需要用ngrok把3000端口映射为公网可达的地址,把这个地址替换到你原有外呼脚本的
url参数里,保证Twilio能正常访问 - 原有外呼发起脚本不需要做逻辑修改,只需要把账号Sid、认证Token、主叫号码、被叫号码替换为你自己的真实值即可
- 不需要额外对接第三方语音识别接口:Twilio的Gather组件已经内置了语音转文字能力,识别完成直接推送文本,减少开发量
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

