媒体流的 URL 格式无效 - 为什么?我可能做错了什么?

问题描述 投票:0回答:1
from flask import Flask, request, Response
import requests
from twilio.twiml.voice_response import VoiceResponse, Play, Start, Stream

from twilio.rest import Client
import time
import os
from google.cloud import speech_v1 as speech
from google.cloud.speech_v1 import types
import threading
import queue
import base64

app = Flask(__name__)

#Google Cloud Credentials environment variable
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './google_credentials.json'

# Twilio credentials
account_sid = ['TWILIO_SID']
auth_token = ['TWILIO_AUTH']
twilio_client = Client(account_sid, auth_token)
speech_client = speech.SpeechClient()

# Create a queue to store audio chunks
audio_chunks_queue = queue.Queue()

# A simple in-memory structure to store call associations
# In production, you might want to use a database
call_associations = {}

response = None

@app.route("/incoming_call", methods=['POST'])
def handle_incoming_call():
    """Responds to incoming calls and sets up segmented recording of inbound audio."""
    response = VoiceResponse()

    start = Start()
    stream = Stream(url='wss://b32e-2603-8081-4c00-3a7c-2d64-d183-b6e6-f523.ngrok-free.app/stream_audio')
    start.append(stream)
    response.append(start)

    twiml_response_str = str(response)
    print("Generated TwiML Response:\n", twiml_response_str)

         
    print("incoming call")
    return Response(str(response), mimetype='text/xml')

@app.route("/stream_audio", methods=['POST'])
def stream_audio():
    """Receive streamed audio from Twilio and add it to the queue."""
    print("Audio is streaming")
    audio_data = request.get_data()
    audio_chunks_queue.put(audio_data)
    return ('', 204)

期望的结果是获得打印语句“音频正在流式传输”,但我是从 Twilio Dashboard 获得的

留言

网址无效。

错误描述

错误 - 11100 ### URL 格式无效 提供的 URL 格式无效。

可能的解决方案 确保您提交完全合格的 URL,包括:

协议(http:// 或 https://) 主机名 文件路径 正确 url 编码的查询参数 Twilio 必须能够通过公共互联网访问此 URL。

可能的原因 电话号码配置的 URL 不正确 传递给拨出呼叫 REST 请求的 URL 错误 播放或重定向动词主体中的错误 URL 为动词的操作属性提供的 URL 不正确 修改实时通话时,记录动词操作属性中未提供 URL URL 的 auth 部分中不支持的字符

我应该使用 https 吗?使用 https 给我同样的错误。还是需要导入库才能使用wss?

python flask twilio
1个回答
0
投票

我认为问题在于您指定了

ws
服务器端点,但您的代码仅在该端点接受
http
。这就是 Twilio 无法向其传输音频的原因。这篇博客文章解释了如何构建与您正在构建的内容相似的东西。

从中,我得到了协调两者的示例文件,以及

http
ws
端点:

const WebSocket = require("ws");
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const wss = new WebSocket.Server({ server });

// Handle Web Socket Connection
wss.on("connection", function connection(ws) {
console.log("New Connection Initiated");

   ws.on("message", function incoming(message) {
    const msg = JSON.parse(message);
    switch (msg.event) {
      case "connected":
        console.log(`A new call has connected.`);
        break;
      case "start":
        console.log(`Starting Media Stream ${msg.streamSid}`);
        break;
      case "media":
        console.log(`Receiving Audio...`)
        break;
      case "stop":
        console.log(`Call Has Ended`);
        break;
    }
  });

};

//Handle HTTP Request
app.get("/", (req, res) => res.send("Hello World");

app.post("/", (req, res) => {
  res.set("Content-Type", "text/xml");

  res.send(`
    <Response>
      <Start>
        <Stream url="wss://${req.headers.host}/"/>
      </Start>
      <Say>I will stream the next 60 seconds of audio through your websocket</Say>
      <Pause length="60" />
    </Response>
  `);
});

console.log("Listening at Port 8080");
server.listen(8080);

© www.soinside.com 2019 - 2024. All rights reserved.