You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
import socket
|
|
import time
|
|
|
|
import simpleaudio as sa
|
|
|
|
HOST = "127.0.0.1"
|
|
PORT = 9000
|
|
|
|
def save_file(client_socket):
|
|
timestamp = str(int(time.time()))
|
|
file_name = f"output_{timestamp}.wav"
|
|
with open(file_name,'wb') as f:
|
|
while True:
|
|
l = client_socket.recv(1024)
|
|
if not l: break
|
|
f.write(l)
|
|
|
|
def play_file(conn):
|
|
# you could consider sa.play_buffer ... I don't know if it would be more performant.
|
|
try:
|
|
wave_object = sa.WaveObject.from_wave_file(conn.makefile(mode="rb"))
|
|
play_obj = wave_object.play()
|
|
play_obj.wait_done()
|
|
except Exception as e:
|
|
print(f"Hit an error: {e} skipping playback")
|
|
return
|
|
|
|
# By default, socket.socket creates TCP sockets.
|
|
with socket.socket() as server_sock:
|
|
# This tells the kernel to reuse sockets that are in `TIME_WAIT` state.
|
|
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
# This tells the socket what address to bind to.
|
|
server_sock.bind((HOST, PORT))
|
|
|
|
# 0 is the number of pending connections the socket may have before
|
|
# new connections are refused. Since this server is going to process
|
|
# one connection at a time, we want to refuse any additional connections.
|
|
server_sock.listen(0)
|
|
print(f"Listening on {HOST}:{PORT}...")
|
|
|
|
while True:
|
|
# This is a blocking call as we wait for a new connection
|
|
client_sock, client_addr = server_sock.accept()
|
|
print(f"New connection from {client_addr}.")
|
|
with client_sock as conn:
|
|
play_file(conn) |