Search code examples
pythonaudioaudio-streamingpyaudio

Playing 2-channel sound with Python PyAudio


I have a problem with pyaudio. I am able to play sound with non-blocking stream only when I set up channel number to 1. When I set it to 2, I can't hear any sound and script exits immadiately. Even if data is mono, shouldn't it play properly? Here is my code fragment:

pa = pyaudio.PyAudio()
out_stream = pa.open(format = pyaudio.paFloat32,
            channels = 2,
            rate = 44100,
            output = True,
            stream_callback = self._output_callback(out_data),
            frames_per_buffer=100)

out_stream.start_stream()
    while(out_stream.is_active()):
        time.sleep(0.1)
    out_stream.stop_stream()

pa.terminate()


@staticmethod
def _output_callback(wav_data):

    def callback(in_data, frame_count, time_info, status):
        pos = callback.pos
        callback.pos += frame_count
        out_data = wav_data[pos:pos+frame_count]
        return (out_data, pyaudio.paContinue)
    callback.pos = 0

    return callback

out_data is numpy array in numpy.float32 format


Solution

  • Ok, I know the reason. I didn't know it before, but after diving a little into pyaudio soruce I realised that in callback function I should return

    frame_count * number_of_channels
    

    frames. So the solution in my case is to insert

    frame_count *= 2      # Because of 2 channels
    

    in the beginning of callback function