白桦的天空

第一次的心动,永远的心痛!
  首页  :: 新随笔  :: 联系 :: 管理

服务端代码:

#!/bin/env python
# -*- coding: utf-8 -*-

import asyncio
import websockets
import time
import threading
import signal
import sys
import pyaudio
import numpy as np
from multiprocessing import Process, Value
import multiprocessing
import ctypes

is_exit = False

def record(voice_rate):
    global is_exit    
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
                    channels=1,
                    rate=16000,
                    input=True,
                    frames_per_buffer=1024)

    while not is_exit:
        data = stream.read(1024)
        audio_data = np.fromstring(data, dtype=np.short)
        max_dB = np.max(audio_data)
        voice_rate.value = max_dB
        time.sleep(0.1)


def sig_handler(signum, frame):
    global is_exit
    is_exit = True
    sys.exit(0)


async def sendData(websocket, path):
    # rev = await websocket.recv()
    # print(f"client: {rev}")    
    await websocket.send(str(voice_rate.value))

if __name__ == "__main__":
    voice_rate = multiprocessing.Manager().Value(ctypes.c_int, 0)
    signal.signal(signal.SIGINT, sig_handler)
    # t = threading.Thread(target=add_variable, args=())
    # t.setDaemon(True)
    # t.start()

    p = Process(target=record, args=(voice_rate,))
    p.start()

    start_server = websockets.serve(sendData, '127.0.0.1', 8765)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

  客户端代码:

import asyncio
import websockets
import time


async def getData():
    uri = "ws://127.0.0.1:8765"
    async with websockets.connect(uri) as websocket:
        await websocket.send("rate")
        ret = await websocket.recv()
        print(f"server: {ret}")
        time.sleep(0.1)
        await getData()

asyncio.get_event_loop().run_until_complete(getData())