You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Twilio API发起通话并提取语音转文本响应(C#实现)

问题解决:Twilio通话自动挂断与语音转文本实现

一、修复通话自动挂断问题

你的现有代码仅用<Say>指令播放语音,执行完成后通话会直接终止。要让接听方能够发言,需在TwiML中添加<Record>指令,让Twilio保持通话并录制用户语音。

修改通话创建代码

替换原TwiML内容,加入录音与转录配置:

using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

namespace CustomerCallerV1._0
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 替换为你的Twilio Account SID和Auth Token
            TwilioClient.Init("你的Account SID", "你的Auth Token");

            var call = CallResource.Create(
                twiml: new Twiml("<Response><Say>Hi, How are you doing? Is that a good time to talk now?</Say><Record transcribe=\"true\" transcribeCallback=\"https://你的公网可访问地址/transcribe\" maxLength=\"60\" /></Response>"),
                to: new PhoneNumber("+12396467367"),
                from: new PhoneNumber("+12396467368")
            );

            Console.WriteLine($"Call SID: {call.Sid}");
        }
    }
}
  • transcribe="true":开启语音转文本功能
  • transcribeCallback:指定Twilio发送转录结果的回调地址(需HTTPS,本地测试可使用ngrok映射端口)
  • maxLength:设置最长录制时长(单位:秒)

二、实现语音转文本提取

需要创建API端点接收Twilio的转录回调,提取并处理文本。以下是ASP.NET Core示例:

1. 创建回调接收控制器

using Microsoft.AspNetCore.Mvc;

namespace YourWebApp.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TranscribeController : ControllerBase
    {
        [HttpPost]
        public IActionResult Post([FromForm] TranscribeRequest request)
        {
            // 提取转录后的文本
            string transcribedContent = request.TranscriptionText;
            string callId = request.CallSid;

            // 此处可将文本保存到数据库、文件或进行业务处理
            Console.WriteLine($"通话{callId}的转录内容: {transcribedContent}");

            // 返回空TwiML结束通话
            return Content("<Response></Response>", "application/xml");
        }
    }

    // 匹配Twilio回调参数的模型
    public class TranscribeRequest
    {
        public string CallSid { get; set; }
        public string TranscriptionText { get; set; }
        public string TranscriptionStatus { get; set; }
        // 可选参数:TranscriptionUrl、RecordingSid等
    }
}

2. 本地测试配置

若在本地开发,使用ngrok将本地端口映射为公网HTTPS地址:

ngrok http 5000

将生成的地址替换到transcribeCallback中,例如https://xxxx-xx-xx-xx-xx.ngrok.io/transcribe

关键注意事项

  • 确保你的Twilio号码支持语音转录功能(部分地区号码需额外开通)
  • 回调地址必须为HTTPS,Twilio不支持HTTP回调
  • 转录结果存在延迟,Twilio完成转录后才会触发回调

内容的提问来源于stack exchange,提问作者samshank102

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 08:17:43