Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import websockets
- import sounddevice as sd
- import numpy as np
- from collections import deque
- import io
- # writing blocks
- async def save_to_file(audio_buffer, file_name):
- with open(file_name, 'ab') as f: # opening file in to append mode
- f.write(audio_buffer + b'\n') # adding new line symbol
- async def consumer(websocket):
- audio_buffer = b''
- duration = 20 # time in sec
- file_name = 'audio_data4.raw'
- try:
- async for data in websocket:
- audio_buffer += data
- # chack if data enought to write
- if len(audio_buffer) >= duration * 8000: # awaited sample_rate
- # start task
- asyncio.create_task(save_to_file(audio_buffer, file_name))
- print(f"Writing to file {file_name} complette, may press CTRL+C.")
- audio_buffer = b'' # reset buffer
- except websockets.exceptions.ConnectionClosed:
- print("connection closed.")
- # writing raw
- #
- # async def save_to_file(audio_buffer, file_name):
- # with open(file_name, 'wb') as f:
- # f.write(audio_buffer)
- #
- # async def consumer(websocket):
- # audio_buffer = b''
- # duration = 20 # Время записи в секундах
- # file_name = 'audio_data3.raw'
- #
- # try:
- # async for data in websocket:
- # audio_buffer += data
- #
- # # Проверяем, достаточно ли данных для записи в файл
- # if len(audio_buffer) >= duration * 10000: # Предполагаемый sample_rate в коде
- # # Запускаем запись в файл в фоновой задаче
- # asyncio.create_task(save_to_file(audio_buffer, file_name))
- #
- # print(f"Запись в файл {file_name} завершена.")
- # break # Заканчиваем запись после достижения указанной длительности
- #
- # except websockets.exceptions.ConnectionClosed:
- # print("Соединение закрыто.")
- # writing raw && converting to int16
- #async def save_to_file(audio_buffer, file_name):
- # with open(file_name, 'wb') as f:
- # # Конвертируем данные в формат int16 перед записью в файл
- # int16_data = (np.frombuffer(audio_buffer, dtype=np.uint8) - 128).astype(np.int8)
- # f.write(int16_data.tobytes())
- #async def consumer(websocket):
- # audio_buffer = b''
- # duration = 20 # Время записи в секундах
- # file_name = 'audio_data1.raw'#
- # try:
- # async for data in websocket:
- # audio_buffer += data
- # Проверяем, достаточно ли данных для записи в файл
- # if len(audio_buffer) >= duration * 10000: # Предполагаемый sample_rate в коде
- # Запускаем запись в файл в фоновой задаче
- # asyncio.create_task(save_to_file(audio_buffer, file_name))
- # print(f"Запись в файл {file_name} завершена.")
- # break # Заканчиваем запись после достижения указанной длительности
- # except websockets.exceptions.ConnectionClosed:
- # print("Соединение закрыто.")
- async def producer(websocket):
- try:
- command = "GET /~~param?f=9590&band=0&lo=-3.5&hi=3.5&mode=1&name=mobile"
- await websocket.send(command)
- print("command send")
- await asyncio.sleep(1)
- except websockets.exceptions.ConnectionClosed:
- print("failure to send command")
- async def connect_to_web_sdr():
- uri = "ws://websdr.ewi.utwente.nl:8901/~~stream"
- try:
- async with websockets.connect(uri, extra_headers=[("Upgrade", "websocket"),
- ("Connection", "Upgrade"),
- ("Pragma", "no-cache"),
- ("Cache-Control", "no-cache"),
- ("User-Agent",
- "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"),
- ("Upgrade", "websocket"),
- ("Origin", "http://websdr.ewi.utwente.nl:8901"),
- ("Sec-WebSocket-Version", "13"),
- ("Accept-Encoding", "gzip, deflate"),
- ("Accept-Language", "ru,en-US;q=0.9,en;q=0.8"),
- # ("Cookie", "ID=65704d658376; view=2"),
- # ("Sec-WebSocket-Key", "r4O2pAoBlr0lwVxwPQx11Q=="),
- ("Sec-WebSocket-Extensions",
- "permessage-deflate; client_max_window_bits")], ping_interval=None) as websocket:
- await asyncio.gather(
- consumer(websocket),
- asyncio.sleep(2),
- producer(websocket),
- )
- await asyncio.Future()
- except Exception as e:
- print(f"error happened: {e}")
- if __name__ == "__main__":
- asyncio.run(connect_to_web_sdr())
Advertisement
Add Comment
Please, Sign In to add comment