通过socket发送wav文件

Send wav files through socket

我正在尝试通过套接字发送 wav 文件。

我收到错误:

TypeError: must be string or buffer, not instance

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'rb')
my_socket.sendall(waveFile)

尝试socket.<strong>sendfile</strong>(<em>file</em>, <em>offset=0</em>, <em>count=None</em>)

Send a file until EOF is reached by using high-performance os.sendfile

并且您不想在发送原始二进制数据时使用 wave.open(...) 打开文件。

所以你会这样做:

with open(WAVE_OUTPUT_FILENAME, 'rb') as wave_file:
    my_socket.sendfile(wave_file)

wave 没有给你通用文件 I/O。它用于获取媒体属性。

您可以使用普通的 open/close、read/write。

sender.py:

import socket

(HOST,PORT)=('localhost',19123)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect((HOST,PORT))

with open('input', 'rb') as f:
  for l in f: s.sendall(l)
s.close()

receiver.py:

import socket

(HOST,PORT) = ('localhost',19123)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT)); s.listen(1); conn, addr = s.accept()

with open('output','wb') as f:
  while True:
    l = conn.recv(1024)
    if not l: break
    f.write(l)
s.close()