我正在尝试记录来自客户端的麦克风输入,然后通过网络发送音频数据。服务器接收此音频数据,并在接收音频时播放音频。
当前,我有一个程序,其中客户端记录音频样本3秒钟。然后将音频样本发送到服务器,该服务器随后将音频数据转换为.wav文件。
服务器:
import socket
import pyaudio
import wave
# Socket
HOST = socket.gethostname()
PORT = 5000
# Audio
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
frames = []
with socket.socket() as server_socket:
server_socket.bind((HOST, PORT))
server_socket.listen(1)
conn, address = server_socket.accept()
print("Connection from " + address[0] + ":" + str(address[1]))
while True:
try:
data = conn.recv(2048)
frames.append(data)
except socket.error as error_message:
break
print(frames)
with wave.open(WAVE_OUTPUT_FILENAME, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
客户:
import socket
import pyaudio
# Socket
HOST = socket.gethostname()
PORT = 5000
# Audio
CHUNK = 1024 * 4
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("Recording")
with socket.socket() as client_socket:
client_socket.connect((HOST, PORT))
while True:
data = stream.read(CHUNK)
client_socket.send(data)
sounddevice
模块有一个名为wire.py的文档示例,它确实完成了服务器端需要执行的操作。但是,该程序的级别似乎很低,我无法理解如何传递用pyaudio
记录的音频数据。
答案 0 :(得分:0)
TYPE testtype
dataArray AS STRING * 8
END TYPE
DIM customtype(10) AS testtype
A = 10: B = 12: C = 14: D = 16
' compress variables into structure
element1$ = MKI$(A) + MKI$(B) + MKI$(C) + MKI$(D)
customtype(1).dataArray = element1$ ' store
' extract variables from structure
element2$ = customtype(1).dataArray ' get
E = CVI(MID$(element2$, 1, 2))
F = CVI(MID$(element2$, 3, 2))
G = CVI(MID$(element2$, 5, 2))
H = CVI(MID$(element2$, 7, 2))
PRINT E, F, G, H
看起来import socket
import pyaudio
# Socket
HOST = socket.gethostname()
PORT = 5000
# Audio
p = pyaudio.PyAudio()
CHUNK = 1024 * 4
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
output=True,
frames_per_buffer=CHUNK)
with socket.socket() as server_socket:
server_socket.bind((HOST, PORT))
server_socket.listen(1)
conn, address = server_socket.accept()
print("Connection from " + address[0] + ":" + str(address[1]))
data = conn.recv(4096)
while data != "":
try:
data = conn.recv(4096)
stream.write(data)
except socket.error:
print("Client Disconnected")
break
stream.stop_stream()
stream.close()
p.terminate()
附带了魔术,其中stream.write(data)
是通过套接字接收的字节对象。 :)