Guest User

Untitled

a guest
Jan 17th, 2024
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.69 KB | Software | 0 0
  1. import asyncio
  2. import websockets
  3. import sounddevice as sd
  4. import numpy as np
  5. from collections import deque
  6.  
  7. import io
  8.  
  9. # writing blocks
  10. async def save_to_file(audio_buffer, file_name):
  11.     with open(file_name, 'ab') as f:  # opening file in to append mode
  12.         f.write(audio_buffer + b'\n')  # adding new line symbol
  13.  
  14. async def consumer(websocket):
  15.     audio_buffer = b''
  16.     duration = 20  # time in sec
  17.     file_name = 'audio_data4.raw'
  18.  
  19.     try:
  20.         async for data in websocket:
  21.             audio_buffer += data
  22.  
  23.             # chack if data enought to write
  24.             if len(audio_buffer) >= duration * 8000:  # awaited sample_rate
  25.                 # start task
  26.                 asyncio.create_task(save_to_file(audio_buffer, file_name))
  27.  
  28.                 print(f"Writing to file {file_name} complette, may press CTRL+C.")
  29.                 audio_buffer = b''  # reset buffer
  30.  
  31.     except websockets.exceptions.ConnectionClosed:
  32.         print("connection closed.")
  33.  
  34.  
  35.  
  36.  
  37. # writing raw
  38. #
  39. # async def save_to_file(audio_buffer, file_name):
  40. #     with open(file_name, 'wb') as f:
  41. #         f.write(audio_buffer)
  42. #
  43. # async def consumer(websocket):
  44. #     audio_buffer = b''
  45. #     duration = 20  # Время записи в секундах
  46. #     file_name = 'audio_data3.raw'
  47. #
  48. #     try:
  49. #         async for data in websocket:
  50. #             audio_buffer += data
  51. #
  52. #             # Проверяем, достаточно ли данных для записи в файл
  53. #             if len(audio_buffer) >= duration * 10000:  # Предполагаемый sample_rate в коде
  54. #                 # Запускаем запись в файл в фоновой задаче
  55. #                 asyncio.create_task(save_to_file(audio_buffer, file_name))
  56. #
  57. #                 print(f"Запись в файл {file_name} завершена.")
  58. #                 break  # Заканчиваем запись после достижения указанной длительности
  59. #
  60. #     except websockets.exceptions.ConnectionClosed:
  61. #         print("Соединение закрыто.")
  62.  
  63.  
  64.  
  65. # writing raw && converting to int16
  66.  
  67. #async def save_to_file(audio_buffer, file_name):
  68. #    with open(file_name, 'wb') as f:
  69. #        # Конвертируем данные в формат int16 перед записью в файл
  70. #        int16_data = (np.frombuffer(audio_buffer, dtype=np.uint8) - 128).astype(np.int8)
  71. #        f.write(int16_data.tobytes())
  72.  
  73. #async def consumer(websocket):
  74. #    audio_buffer = b''
  75. #    duration = 20  # Время записи в секундах
  76. #    file_name = 'audio_data1.raw'#
  77.  
  78. #    try:
  79. #        async for data in websocket:
  80. #            audio_buffer += data
  81.  
  82.             # Проверяем, достаточно ли данных для записи в файл
  83. #            if len(audio_buffer) >= duration * 10000:  # Предполагаемый sample_rate в коде
  84.                 # Запускаем запись в файл в фоновой задаче
  85. #                asyncio.create_task(save_to_file(audio_buffer, file_name))
  86.  
  87. #                print(f"Запись в файл {file_name} завершена.")
  88. #                break  # Заканчиваем запись после достижения указанной длительности
  89.  
  90. #    except websockets.exceptions.ConnectionClosed:
  91. #        print("Соединение закрыто.")
  92.  
  93.  
  94.  
  95. async def producer(websocket):
  96.     try:
  97.         command = "GET /~~param?f=9590&band=0&lo=-3.5&hi=3.5&mode=1&name=mobile"
  98.         await websocket.send(command)
  99.         print("command send")
  100.         await asyncio.sleep(1)
  101.     except websockets.exceptions.ConnectionClosed:
  102.         print("failure to send command")
  103.  
  104.  
  105. async def connect_to_web_sdr():
  106.     uri = "ws://websdr.ewi.utwente.nl:8901/~~stream"
  107.  
  108.     try:
  109.         async with websockets.connect(uri, extra_headers=[("Upgrade", "websocket"),
  110.                                                           ("Connection", "Upgrade"),
  111.                                                           ("Pragma", "no-cache"),
  112.                                                           ("Cache-Control", "no-cache"),
  113.                                                           ("User-Agent",
  114.                                                            "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"),
  115.                                                           ("Upgrade", "websocket"),
  116.                                                           ("Origin", "http://websdr.ewi.utwente.nl:8901"),
  117.                                                           ("Sec-WebSocket-Version", "13"),
  118.                                                           ("Accept-Encoding", "gzip, deflate"),
  119.                                                           ("Accept-Language", "ru,en-US;q=0.9,en;q=0.8"),
  120.                                                           # ("Cookie", "ID=65704d658376; view=2"),
  121.                                                           # ("Sec-WebSocket-Key", "r4O2pAoBlr0lwVxwPQx11Q=="),
  122.                                                           ("Sec-WebSocket-Extensions",
  123.                                                            "permessage-deflate; client_max_window_bits")], ping_interval=None) as websocket:
  124.  
  125.  
  126.             await asyncio.gather(
  127.                 consumer(websocket),
  128.                 asyncio.sleep(2),
  129.                 producer(websocket),
  130.             )
  131.             await asyncio.Future()
  132.     except Exception as e:
  133.         print(f"error happened: {e}")
  134.  
  135.  
  136.  
  137.  
  138.  
  139. if __name__ == "__main__":
  140.     asyncio.run(connect_to_web_sdr())
  141.  
Advertisement
Add Comment
Please, Sign In to add comment