Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyaudio Recording audio from streaming Python

I would like to record using pyaudio in python, the audio streamed through a socket and save it in a *.wav file. I want to save everything in wave after so I can process it as I want. For now I have tried to write this code, but it always fails after a while that I compile.

The error is

wf.writeframes(b''.join(data1))
TypeError: sequence item 0: expected bytes, int found

my code for client.py is:

import pyaudio, sys, socket, wave
port = 5000
ip = "192.168.1.110"
chunk = 512
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 49000
WAVE_OUTPUT="output.wav"

p = pyaudio.PyAudio()
stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input =True,output = True, frames_per_buffer = chunk)

#Create a socket connection for connecting to the server:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((ip, port))
print ("***Registrazione in corso***")
frames=[]
for i in range (0,int(RATE/chunk*20)):
data1=client_socket.recv(chunk)
frames.append(data1)
while True:
#Recieve data from the server:
#data = client_socket.recv(1024)
stream.write(data1,chunk)
wf=wave.open(WAVE_OUTPUT,"wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(data1))
#print data
wf.close()   
socket.close()
like image 381
Marco Avatar asked Mar 09 '26 12:03

Marco


1 Answers

You are getting a TypeError because the open wav file want a stream of bytes and you are passing a single int value. I think you want to write the entire frame to the file and not just the chunk in data1. Try wf.writeframes(b''.join(frames)). Also don't forget to close the stream at the end.

stream.stop_stream() stream.close()

like image 187
Steven Correia Avatar answered Mar 12 '26 01:03

Steven Correia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!