我想停止发送到 Twilio 的音频。 我有一个代码,可将音频响应从 11 个实验室流式传输到 Twilio WS 呼叫。 这是我开始通话的方式:
@application.post('/call')
async def handle_incoming_calls(request: Request, From: Annotated[str, Form()]): response = VoiceResponse()
connect = Connect()
URL = f"wss://{PUBLIC_URL}/stream"
STATUS_URL = f"https://{PUBLIC_URL}/status-call"
connect.stream(url=URL,status_callback=STATUS_URL,status_callback_method='POST',name=str("<name>"))
response.append(connect)
return Response(content=str(response), media_type='text/xml')
更多代码处理消息,生成对用户输入的 AI 响应,然后我将 11 个实验室语音传输到 TWILIO 呼叫,如下所示:
async def stream(audio_stream, twilio_ws, stream_sid,call_sid):
global send_stream_task
print(f"\n\nNew streamSID: {stream_sid}\n\n")
async for chunk in audio_stream:
if chunk:
audio = chunk
b64_audio = base64.b64encode(audio).decode('utf-8')
message = json.dumps({'event': 'media', 'streamSid': stream_sid,
'media': {'payload': b64_audio, }})
send_stream_task[call_sid] = asyncio.create_task(twilio_ws.send_text(message))
await send_stream_task[call_sid]
即使我停止流功能,它已经发送的数据也会在 Twilio 调用中播放 我正在执行以下操作来停止该功能:
listen_task = {} # init listen task with dict
send_to_tts = {} #init sent tts task with dict send_stream_task = {} # init send stream task with dict
async def cancel_tasks(call_sid,stream_sid): global listen_task,send_to_tts,send_stream_task
if call_sid in send_stream_task:
if send_stream_task[call_sid].cancel():
print("\n\nsend stream cancelled correctly\n\n")
if call_sid in listen_task:
if listen_task[call_sid].cancel():
print("Stream Sid: ",stream_sid)
print("\n\nlisten canelled correctly\n\n")
#stop_media_stream(call_sid, stream_sid)
if call_sid in send_to_tts:
if send_to_tts[call_sid].cancel():
#del listen_task[call_sid]
print("\n\nsend to TTS cancelled correctly\n\n")
当我收到新的用户输入时,我运行它,它会停止当前正在运行的功能。 但我已经发送给呼叫的数据仍在播放。 我尝试使用以下函数来停止流,但只收到 404 错误:
def stop_media_stream(call_sid, stream_sid):
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
stream = client.calls(str(call_sid)) \
.streams(str(stream_sid)) \
.update(status='stopped')
错误信息:
HTTP Error Your request was:
POST /Accounts/<ACCOUND_SID>/Calls/<CALL_SID>/Streams/<STREAM_SID>.json
Twilio returned the following information:
Unable to update record: The requested resource /2010-04-01/Accounts/<ACCOUND_SID>/Calls/<CALL_SID>/Streams/<STREAM_SID>.json was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
stop_media_stream 函数会停止媒体流,但不会停止播放已经流式传输的音频。
这样做的问题是我可以在几秒钟内发送 1 分钟的音频,所以即使我停止流,我仍然会听到一段时间的音频。 有人知道另一种方法吗?
要停止播放媒体流,您可以使用清除消息 - https://www.twilio.com/docs/voice/twiml/stream#message-clear-to-twilio
只需发送一条 JSON 消息:
{
"event": "clear",
"streamSid": "<STREAM_ID>",
}