我想通过HTTP发送音频数据,但我不明白为什么会收到此异常:
Exception happened during processing of request from ('127.0.0.1', 59976) Traceback (most recent call last): File "/usr/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/usr/lib/python3.6/http/server.py", line 418, in handle self.handle_one_request() File "/usr/lib/python3.6/http/server.py", line 406, in handle_one_request method() File "/home/vivanov/temp.py", line 113, in do_GET data.append(bytearray(stream.read(CHUNK))) TypeError: 'bytearray' object cannot be interpreted as an integer
问题似乎与将值传递给wfile.write
有关。
如何解决该问题?
这是我的代码:
class ChunkingRequestHandler(BaseHTTPRequestHandler):
ALWAYS_SEND_SOME = False
ALLOW_GZIP = False
protocol_version = 'HTTP/1.1'
def do_GET(self):
ae = self.headers.get('accept-encoding') or ''
# send some headers
self.send_response(200)
self.send_header('Transfer-Encoding', 'chunked')
self.send_header('Content-type', 'audio/x-wav')
self.end_headers()
data = bytearray(wav_header)
data.append(bytearray(stream.read(CHUNK)))
print(data)
self.wfile.write(b"%X\r\n%s\r\n" % (len(data), data))
while True:
data = bytearray(stream.read(CHUNK))
self.wfile.write(b"%X\r\n%s\r\n" % (len(data), data))
# send the chunked trailer
self.wfile.write('0\r\n\r\n')
答案 0 :(得分:1)
尽管有其名称,但是如果您想一次将多个元素附加到Python中的类似列表的对象,则不能使用append
方法。 bytearray
的行为就像一个字节列表,因此在其上附加或连接另一个bytearray
的方法是使用extend
方法或+=
:
data += bytearray(...)
# OR
data.extend(bytearray(...))
实际上,如果您要添加到bytearray
的内容已经可以传递到bytearray()
构造函数中,则可能不需要将其包装在{{1}中}。例如,可以直接添加bytearray()
个对象(例如bytes
)
b'something'
修复了该行代码后,其他行可能会出现问题。例如,如果data += b'something'
占用wfile.write
,则向其发送诸如bytes
之类的unicode字符串可能会出错;看来您打算写'0\r\n\r\n'
。
答案 1 :(得分:0)
实际上,这是我最终工作的最终代码,可能对某人有用:
class ChunkingRequestHandler(BaseHTTPRequestHandler):
ALWAYS_SEND_SOME = False
ALLOW_GZIP = False
protocol_version = 'HTTP/1.1'
def do_GET(self):
ae = self.headers.get('accept-encoding') or ''
# send some headers
self.send_response(200)
self.send_header('Content-type', 'audio/x-wav')
self.end_headers()
data = []
for i in wav_header:
data.append(int(i))
for i in stream.read(CHUNK):
data.append(int(i))
self.wfile.write(bytearray(data))
while True:
data = []
for i in stream.read(CHUNK):
data.append(int(i))
self.wfile.write(bytearray(data))
# send the chunked trailer
self.wfile.write('0\r\n\r\n')