Implements a TCP server for audio streaming and sample I/O. Supports both audio files and microphone/speaker devices as input/output. Listens for commands from a client (such as setting mode, filename, configuring stream, enabling/disabling stream, reading/writing audio data), and perfo
| 57 | MODE_AUDIO_OUTPUT = 1 |
| 58 | |
| 59 | class AudioServer: |
| 60 | """Implements a TCP server for audio streaming and sample I/O. |
| 61 | |
| 62 | Supports both audio files and microphone/speaker devices as input/output. |
| 63 | Listens for commands from a client (such as setting mode, filename, configuring stream, |
| 64 | enabling/disabling stream, reading/writing audio data), and performs the requested audio |
| 65 | operations using PyAudio and wave modules. |
| 66 | """ |
| 67 | def __init__(self, address, authkey): |
| 68 | """ |
| 69 | Initialize the AudioServer. |
| 70 | |
| 71 | Sets up command codes, audio format constants, and initializes all state variables. |
| 72 | Creates a Listener object for incoming client connections. |
| 73 | Args: |
| 74 | address: The (IP, port) tuple for the server to listen on. |
| 75 | authkey: The authorization key for client connections. |
| 76 | Returns: |
| 77 | None |
| 78 | """ |
| 79 | # Server commands |
| 80 | self.SET_MODE = 1 |
| 81 | self.SET_DEVICE = 2 |
| 82 | self.SET_FILENAME = 3 |
| 83 | self.STREAM_CONFIGURE = 4 |
| 84 | self.STREAM_ENABLE = 5 |
| 85 | self.STREAM_DISABLE = 6 |
| 86 | self.AUDIO_READ = 7 |
| 87 | self.AUDIO_WRITE = 8 |
| 88 | self.CLOSE_SERVER = 9 |
| 89 | |
| 90 | # Variables |
| 91 | self.listener = Listener(address, authkey=authkey.encode('utf-8')) |
| 92 | self.device = 0 |
| 93 | self.filename = None |
| 94 | self.mode = MODE_AUDIO_INPUT |
| 95 | self.active = False |
| 96 | self.eos = False |
| 97 | self.stream = None |
| 98 | self.wave_file = None |
| 99 | self.pyaudio_obj = pyaudio.PyAudio() |
| 100 | self.audio_buffer = bytearray() |
| 101 | self.chunk_size = 1024 |
| 102 | |
| 103 | # Stream configuration |
| 104 | self.channels = None |
| 105 | self.sample_rate = None |
| 106 | self.sample_bits = None |
| 107 | |
| 108 | def _setMode(self, mode): |
| 109 | """ |
| 110 | Set the stream mode to input (microphone/file) or output (speakers/file). |
| 111 | |
| 112 | Args: |
| 113 | mode: The I/O mode (input or output). |
| 114 | Returns: |
| 115 | Current mode value. |
| 116 | """ |