3

I'm using a Logitech usb headset (http://www.amazon.com/gp/product/B000UXZQ42?psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00) to record and playback audio.

I need non-blocking playback because I want the user to be able to control the playback.

Based on the examples from http://people.csail.mit.edu/hubert/pyaudio/docs/ I've got recording working fine in calback mode.

Playback works nicely in blocking mode but the following code produces choppy distorted audio.

import pyaudio
import wave
import time

CHUNK = 256
WAVE_OUTPUT_FILENAME = 'output.wav'

pa = pyaudio.PyAudio()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'rb')

def playingCallback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    return (data, pyaudio.paContinue)

stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
                 channels=wf.getnchannels(),
                 rate=wf.getframerate(),
                 output=True,
                 frames_per_buffer=CHUNK,
                 output_device_index=2,
                 stream_callback=playingCallback)

stream.start_stream()

while stream.is_active():
    time.sleep(0.5)

stream.stop_stream()
stream.close()
wf.close()

pa.terminate()
2

Your sound distortion is coming from your while loop. By calling the sleep function, you're telling your program do nothing for half a second, and then come back.

If we look at their blocking example, you can see they handle the loop differently:

# read data
data = wf.readframes(CHUNK)

while len(data) > 0:
    stream.write(data)
    data = wf.readframes(CHUNK)
  • 1
    Thanks @Jacobm001. I had that thought but, in callback mode stream.start_stream() starts calling playingCallback in another thread. The time.sleep(0.5) is just keeping the main thread alive until the stream is done. Changing 0.5 to '0.1' or '1.0' has no effect on the 'choppyness' of the playback. – Hector Scout Feb 1 '16 at 15:18
2

Try increasing the chunk size argument to be 0.5-1 second. I.E if you are playing at a 16000hz audio rate, set chunk size to 8000.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.