Package: pastream
GIL-less Portaudio Streams for Pythonpastreambuilds on top ofportaudioand the
excellentsounddevicepython bindings to provide some more advanced functionality right out of the
box. Note that in addition to the pastreamlibrary, pastream includes acommand line applicationfor playing
and recording audio files.Documentation:http://pastream.readthedocs.io/Source code repository and issue tracker:http://github.com/tgarc/pastream/FeaturesGIL-less Audio CallbacksHaving the portaudio callback implemented in C means audio interrupts can
be serviced quickly and reliably without ever needing to acquire the Python
Global Interpreter Lock (GIL). This is crucial when working with libraries
likePillowwhich may greedily grab and
hold the GIL subsequently causing audio overruns/underruns.Input Stream iteratorsEfficiently retrieve live audio capture data through an iterable. As simple as:importpastreamaspsforchunkinps.chunks():process(chunk)Seepastream.chunksandpastream.InputStream.chunksmethod.Built-in support for working with SoundFiles and numpy ndarraysSeamless support for playback/recording of numpy ndarrays, generic buffer
types, and SoundFiles.Reader/Writer Threadspastream simplifies the process of implementing stream reader and writer
threads to manipulate and/or generate data in the background while leaving
the main thread free for higher level management tasks.External DependenciesThere are a few compiled libraries pastream requires whichmayneed to be
installed separately depending on your operating system. Windows users are
luckiest, they can skip this section entirely.libffi(Linux/Unix/MacOSX):Under Linux/Unix/MacOSX platforms you’ll need to install the ffi
library. (For Windows users, ffi is already included with the python cffi
package.)  libffi is available through most package managers:$ yum install libffi-devel # Red-hat/CentOS Linux
$ apt-get install libffi-dev # Ubuntu/debian derivatives
$ brew install libffi # Homebrew on OSXMore information on installinglibffiis available in the cffi
documentationhere.PortAudioandlibsndfile(Linux/Unix):Linux and Unix users will also need to install a recent version of thePortAudioandlibsndfilelibraries. (For Windows and OSX, the
sounddevice and soundfile python packages include prebuilt versions for
you.) You can either install the latest available from your package manager
(e.g.apt-getinstall libportaudio2 libsndfilefor debian/raspbian) or
install the latest stable build from the package website (Recommended).InstallationOnce the above dependencies have been resolved, you can install pastream using
pip:$ pip install pastreamBuilding From SourceClone pastream with the--recursiveflag:$ git clone --recursive http://github.com/tgarc/pastreamOr, if you already have a checkout:$ cd <path/to/checkout>
$ git submodule update --initFinally, do a pip install from your local working copy:$ pip install <path/to/checkout>Building DocumentationDocumentation for pastream can be easily generated in a wide variety of formats
using Sphinx. Just follow the steps below.Checkout the repository and cd into it:$ git clone http://github.com/tgarc/pastream
$ cd pastreamInstall documentation dependencies using requirements file:$ pip install -r docs/requirements.txtThen use the included Makefile/make.bat to generate documentation. (Here we
output to the html format):$ cd docs
$ make htmlExamplesRecord one second of audio to memory, then play it back:importpastreamasps# Use *with* statements to auto-close the streamwithps.DuplexStream()asstream:out=stream.record(int(stream.samplerate),blocking=True)stream.play(out,blocking=True)Playback 10 seconds of a file, adding zero padding if the file is shorter, and
record the result to memory:importpastreamasps,soundfileassfwithsf.SoundFile('my-file.wav')asinfile,ps.DuplexStream.from_file(infile)asstream:out=stream.playrec(infile,frames=10*int(stream.samplerate),pad=-1,blocking=True)Grab (real) frequency transformed live audio stream with 50% overlap:importpastreamasps,numpyasnpchunksize=1024window=np.hanning(chunksize)forx_linps.chunks(chunksize,overlap=chunksize//2,channels=1):X_l=np.fft.rfft(x_l*window)Generate a pure tone on-the-flyimporttimeimportpastreamaspsimportnumpyasnp# A simple tone generatordeftone_generator(stream,buffer,f,loop=False):fs=stream.samplerate# Create a time indext=2*np.pi*f*np.arange(len(buffer),dtype=stream.dtype)/fs# Loop until the stream stopswhilenotstream.finished:frames=buffer.write_availableifnotframes:time.sleep(0.010)continue# Get the write buffers directly to avoid making any extra copiesframes,part1,part2=buffer.get_write_buffers(frames)out=np.frombuffer(part1,dtype=stream.dtype)np.sin(t[:len(out)],out=out)iflen(part2):# part2 will be nonempty whenever we wrap around the end of the ring bufferout=np.frombuffer(part2,dtype=stream.dtype)np.sin(t[:len(out)],out=out)# flag that we've added data to the bufferbuffer.advance_write_index(frames)# advance the time indext+=2*np.pi*f*frames/fswithps.OutputStream(channels=1)asstream:# Set our tone generator as the source and pass along the frequencyfreq=1000stream.set_source(tone_generator,args=(freq,))# Busy-wait to allow for keyboard interruptstream.start()whilestream.active:time.sleep(0.1)See also the included examples under/examples.Command Line ApplicationOnce installed, the pastream application should be callable from your command
line. If you’re familiar withSoXyou’ll
notice that some of the command line syntax is quite similar. Here are a few
examples to help get you started.Display the help file:$ pastream -hList available audio devices:$ pastream -lSimultaneous play and record from the default audio device:$ pastream input.wav output.wavPipe input from sox using the AU format and record the playback:$ sox -n -t au - synth sine 440 | pastream - output.wavPlay a RAW file:$ pastream -c1 -r48k -e=pcm_16 output.rawRecord 10 minutes of audio at 48kHz:$ pastream null output.wav -r48k -d10:00