【问题标题】:Send wav files through socket通过socket发送wav文件
【发布时间】:2016-11-20 16:36:45
【问题描述】:

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

我得到错误:

TypeError: must be string or buffer, not instance

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

【问题讨论】:

  • 我上面写的代码,my_socket.send(),wavefile=open(...).read()

标签: python python-2.7 sockets wav wave


【解决方案1】:

wave 不提供通用文件 I/O。用于获取媒体属性。

您可以只使用正常的打开/关闭、读/写。

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()

【讨论】:

  • clients code: 'while data: alldata+=data data=client_socket.recv(1024) voice=open("voice.p",'wb') voice.write(alldata)' error-wave.Error: 文件不以 RIFF id 开头
  • 我将send 更改为sendall。前者不能保证发送所有字节(并且需要用剩余的字节重试)。后者发送所有字节。它不需要重试。
  • 在客户端,不要做字符串操作,比如alldata+=data;。我不认为它们在字节数组上是安全的。
  • 那么我应该在客户端做什么?
  • @user4719989,添加了完整的发送者和接收者组合的代码。
【解决方案2】:

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

使用高性能os.sendfile 发送文件直到到达 EOF ……

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

所以你会这样做:

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

【讨论】:

  • 它向我提出了错误 error-AttributeError: '_socketobject' object has no attribute 'sendfile'
  • 我正在使用 windows ir 它的问题
  • socket.sendfile() 在 Python 2.7 中不退出。
猜你喜欢
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2021-07-09
  • 2015-10-04
  • 2015-11-19
  • 2018-10-19
  • 1970-01-01
  • 2015-11-17
相关资源
最近更新 更多