pythonpyaudiorecordingchannelsoundcard

Python PyAudio is Processing all data into one channel


I am using pyaudio to record data from a two channel soundcard using this function

 def record(self):
        '''
        Record Function reads from stream with configured soundcard and stores items in an array
        uses callback function as can be told to stop recording during stream. After ending writes contents 
        to wav file
        '''
        wf = wave.open('audiooutput.wav', 'wb')
        wf.setnchannels(2)
        wf.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
        wf.setframerate(44100)
        p = pyaudio.PyAudio()
        frames = []
        # sub function checks the queue for a message to stop recording
        def check_for_recordstop():
            try:
                message = self.my_queue.get(timeout = 0.1)
            except:
                return 
            if message == None:
                pass
            elif message.payload == "Stop":
                self.confirm_message_recieved(message)
                stream.stop_stream()
        #subfunction callback         
        def callback(in_data, frame_count, time_info, status):
            if stream.is_active():
                frames.append(in_data)
                return (in_data, pyaudio.paContinue)
            else:
                frames.append(in_data)
                return (in_data, pyaudio.paComplete)

        stream = p.open(format=pyaudio.get_sample_size(pyaudio.paInt16),
                        channels= 2,
                        rate=44100,
                        input=True,
                        frames_per_buffer=1024,
                        input_device_index=1,
                        stream_callback = callback)

        self.logger.info("Recording")
        stream.start_stream() # callback is run on a new thread when start_stream() is triggered

        while stream.is_active(): #Loop to keep thread alive while callback is running

            time.sleep(0.1)
            check_for_recordstop()
        print("done")    

        stream.close()
        wf.writeframes(b''.join(frames))
        wf.close()
        p.terminate()

However when viewing this data in audacity I do not end up with 2 channel stream it looks like thisenter image description here

But When using a Function like this

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                input_device_index=1,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open("pyaudoutput.wav", 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

the audio data comes out as expected see here enter image description here

I cannot seem to get the first function to produce the desired results from the second! I need to use the callback capability of pyaudio for my usecase but cannot get the two channels to separate. Any Advice would be great!


Solution

  • I was opening the stream using the sample size not the sample width

    format=pyaudio.get_sample_size(pyaudio.paInt16),
    

    should be

    format=pyaudio.get_format_from_width(wf.getsampwidth()),
    

    using the sample width from the file I writing to solved the issue