websocket 使用http或mqtt调用启动和停止音频流-Python

axr492tv  于 2023-06-23  发布在  Python
关注(0)|答案(1)|浏览(165)

我有一个python脚本,可以流式传输音频。它使用websockets,asyncio和pyaudio。我想启动和停止流或这个完整的脚本与HTTP或MQTT调用。目前我正在做的是手动操作,即。开始:python script.py停止:Ctrl C
我该用什么方法?

# starts recording
stream = p.open(
   format=FORMAT,
   channels=CHANNELS,
   rate=RATE,
   input=True,
   frames_per_buffer=FRAMES_PER_BUFFER
)

async def send_receive():
   print(f'Connecting websocket to url ${URL}')
   async with websockets.connect(
       URL,
       extra_headers=(("Authorization", auth_key),),
       ping_interval=5,
       ping_timeout=20
   ) as _ws:
       await asyncio.sleep(0.1)
       print("Receiving SessionBegins ...")
       session_begins = await _ws.recv()
       print(session_begins)
       print("Sending messages ...")
       async def send():
           while True:
               try:
                   data = stream.read(FRAMES_PER_BUFFER)
                   data = base64.b64encode(data).decode("utf-8")
                   json_data = json.dumps({"audio_data":str(data)})
                   await _ws.send(json_data)
               except websockets.exceptions.ConnectionClosedError as e:
                   print(e)
                   assert e.code == 4008
                   break
               except Exception as e:
                   assert False, "Not a websocket 4008 error"
               await asyncio.sleep(0.01)

           return True

       async def receive():
           while True:
               try:
                   result_str = await _ws.recv()
                   print(json.loads(result_str)['text'])
               except websockets.exceptions.ConnectionClosedError as e:
                   print(e)
                   assert e.code == 4008
                   break
               except Exception as e:
                   assert False, "Not a websocket 4008 error"

       send_result, receive_result = await asyncio.gather(send(), receive())

asyncio.run(send_receive())
vbopmzt1

vbopmzt11#

要使用HTTP调用启动和停止Python脚本,您可以设置一个Web服务器,该服务器侦听特定请求以触发脚本的执行或终止。下面是一个使用Flask框架的基本示例:
安装 flask :

pip install flask

创建一个新的Python文件,例如script_controller.py,并导入必要的模块:

from flask import Flask, request
import subprocess

app = Flask(__name__)
process = None

定义用于启动和停止脚本的路由处理程序:

@app.route('/start_script', methods=['POST'])
def start_script():
    global process
    if process is None or process.poll() is not None:
        # Start the script if it's not already running
        process = subprocess.Popen(['python', 'your_script.py'])
        return 'Script started successfully.'
    else:
        return 'Script is already running.'

@app.route('/stop_script', methods=['POST'])
def stop_script():
    global process
    if process and process.poll() is None:
        # Terminate the script if it's running
        process.terminate()
        return 'Script stopped successfully.'
    else:
        return 'Script is not running.'

if __name__ == '__main__':
    app.run()

将start_script路由处理程序中的'your_script.py'替换为您要执行的脚本的文件名。
通过运行script_controller.py文件启动Web服务器:

python script_controller.py

服务器运行后,您可以发送HTTP请求来启动或停止脚本:
要启动脚本,请执行以下操作:

POST http://localhost:5000/start_script

要停止脚本,请执行以下操作:

POST http://localhost:5000/stop_script

相关问题