S
S
sswwssww2020-04-22 11:09:34
Python
sswwssww, 2020-04-22 11:09:34

What is the correct way to send .wav to the client using socket?

def get_audio(filename):
    with open(filename, 'r', encoding='ansi') as audio:
        content = audio.read()
    return content
...
content = get_audio(filename=yandex_audio_name) 
response_for_client = f'HTTP/1.1\r\nContent-Type: audio/mpeg\r\nContent-Disposition: ' \
                                   f'attachment; filename="1.wav"\r\nTransfer-Encoding: chunked;'\
                                   f'charset=ansi\r\n\r\n{content}'.encode('ansi')
...
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((MY_LOCAL_IP, 5000))
    server_socket.listen()

    while True:
        client_socket, client_addr = server_socket.accept()
        request = client_socket.recv(1024)
        response_for_client = response(request)

        if response_for_client:
            client_socket.sendall(response_for_client)

        client_socket.close()

- there is such a code, I start the server, send a request to the server through the browser, I get the file, BUT when it is played, it sometimes hisses, squeaks. I open through notepad ++ the file that I sent from the server and which I received, the content is the same, the encoding is the same, but 5 bytes are lost somewhere in the downloaded file, but I can’t find where. I compare them through WinMerge - it says that the files are identical. The bitrate of the transferred file is 48000 Hz. I can’t understand what’s the matter, either in encodings, or you need to explicitly specify the bitrate in the headers. Tell me, where can be a catch?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-04-22
@trapwalker

Sound in this format is binary data. You can not work with them as with text.
You open the file in text mode. Do not do it this way. Open in binary, do not decode. Send as bytes. Accept also as bytes.
For example, paragraph characters can be interpreted incorrectly and replaced, pieces of data will move out of this, alignment will break.
I didn't understand. you are imitating part of the http protocol on sockets. What for? Send either from socket to socket in its purest form, or raise a trivial server to flask and use requests so as not to reinvent the dendro-fecal wheel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question