[每个人,我正在尝试在树莓派3的终端之间进行一些语音流传输,我能够使用一些python代码并实现该目标,但问题是我正在使用TCP,所以存在一些延迟,我想改用UDP每当我改变时都会遇到问题将socket.SOCK_STREAM转换为DGRAM并删除serversocket.listen(5),代码可以正常工作,但是没有连接。
服务器
import socket
import select
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
audio = pyaudio.PyAudio()
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 4444))
serversocket.listen(5)
def callback(in_data, frame_count, time_info, status):
for s in read_list[1:]:
s.send(in_data)
return (None, pyaudio.paContinue)
# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, stream_callback=callback)
# stream.start_stream()
read_list = [serversocket]
print ("recording...")
try:
while True:
readable, writable, errored = select.select(read_list, [], [])
for s in readable:
if s is serversocket:
(clientsocket, address) = serversocket.accept()
read_list.append(clientsocket)
print ("Connection from", address)
else:
data = s.recv(1024)
if not data:
read_list.remove(s)
except KeyboardInterrupt:
pass
print ("finished recording")
serversocket.close()
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
客户
#!/usr/bin/env python
import pyaudio
import socket
import sys
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((192.168.1.120, 5555))
audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True, frames_per_buffer=CHUNK)
try:
while True:
data = s.recv(CHUNK)
stream.write(data)
except KeyboardInterrupt:
pass
print('Shutting down')
s.close()
stream.close()
audio.terminate()
代码有效
那是什么意思?是否正在发送/接收数据?UDP是connectionless protocol,因此没有连接是有意义的。