I am trying to make a footswitch that controls the recording on a PC. The input from the footswitch goes to one channel (the control channel) and the input from the musician would go to the other channel. These channels are connected with the Line-in of the sound card.
When some actions are detected from the footswitch the program should initiate recording from the musician’s channel and then play it back.
The program below works but when using the stream.write(…) to playback the recorded stream it plays at a faster rate than the original.
I am a beginner in Python so my programming is very bad!
import pyaudio import time import numpy as np CHUNK = 1024 #Bytes CHANNELS = 2 #Channels RATE = 44100 #Frames/sec FORMAT = pyaudio.paFloat32 #Frame= 4Bytes/channel p = pyaudio.PyAudio()#instatiates PyAudio object which sets up the portaudio system # open stream object as input & output-to record/play audio stream = p.open(format=FORMAT, channels=CHANNELS, input_device_index=1, output_device_index=3, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK) record_seconds = int(input("Give me recording time: ")) print("* recording") pressed =  #intitialize array to store duration that the footswitch is pressed count=0 #counts press of footswitch s=0 #counts short press of footswitch l=0 #counts long press of footswitch i=0 #time divisions of the buffer frames =  #initialize array to record frames while i <= int(RATE / CHUNK * record_seconds):#44100x4Bytes/1024 per channel data = stream.read(CHUNK,exception_on_overflow=False)#read audio data from the stream sIN = np.frombuffer(data, dtype = np.float32)#creates an array of floats from the buffer ctrlCH=sIN[2::CHANNELS] sCTRL=np.sqrt(np.sum(ctrlCH**2)) rightCH=sIN[1::CHANNELS] dataR=rightCH.tobytes() if(sCTRL>0.5): count = count + 1 else: count = 0 pressed.append(count) if(i>1): if (pressed[i-1]>=3 and pressed[i-1]<=10 and pressed[i]<3): s=s+1 if (s==1): print("Recording ",s, "...") elif (s==2): print ("Stopped recording") if(s==1): frames.append(dataR) #store data elif (s==2): stream.write(b''.join(frames))# write the frames as bytes i+=1 print("* done") time.sleep(1) stream.stop_stream()#pause playing/recording stream.close()#terminate the stream p.terminate()#terminate portaudio session
Source: Python Questions