使用Twilio Serverless SDK本地部署音频服务遇阻求助
问题:Twilio Serverless本地部署时,Buffer被序列化为JSON,无法返回原始音频数据
我基于Twilio Serverless SDK开发了一个返回音频文件的函数,在Twilio控制台服务编辑器中运行正常,但本地用Serverless SDK部署后完全失效。
资源与代码实现
- 私有资源:MP3音频文件存放在
assets/hello.mp3 - 公开函数:
functions/handler.js代码如下:
const fs = require('fs'); exports.handler = function(context, event, callback) { var phrase = event.phrase; var filePath = Runtime.getAssets()[`/${phrase}.mp3`].path; var buffer = fs.readFileSync(filePath); var stat = fs.statSync(filePath); var response = new Twilio.Response(); response.setBody(buffer); response.appendHeader('Content-Type', 'audio/mpeg'); response.appendHeader('Content-Length', stat.size); return callback(null, response); };
和官方示例的唯一区别是,我允许通过GET参数phrase指定要返回的音频文件名。
问题现象
请求http://localhost:3000/handler?phrase=hello时,Chrome识别到是音频文件但无法加载播放,响应内容是Buffer的JSON序列化结果:
{ "type": "Buffer", "data": [255, 243, 68, 196, 0, 17, 82, 130, 20, 0, 24, 68, 185, 52, 68, 74, 44, 234, 110, 238, 250, 23, 204,…] }
这说明Buffer被转成了JSON而非原始二进制音频数据。请求无错误,HTTP状态码为200,响应头如下:
HTTP/1.1 200 OK X-Powered-By: Express Surrogate-Control: no-store Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate Pragma: no-cache Expires: 0 Content-Type: audio/mpeg; charset=utf-8 Content-Length: 27077 ETag: W/"69c5-hX8H/5UaULdPYVqq2abJK7EeJmg" Date: Mon, 22 Aug 2022 21:03:35 GMT Connection: keep-alive Keep-Alive: timeout=5
已尝试的解决方案(均无效)
- 尝试
buffer.toString()的多种编码格式(如binary、base64) - 改用文件流返回数据
额外需求
我需要在通话中播放大量语句,计划把短句作为私有资源存储并快速拼接,避免连续使用TwiML<Play>动词导致的停顿,希望解决方案能兼容这个场景。
内容的提问来源于stack exchange,提问作者dh182
相关产品推荐
相关产品推荐

