Package: pasimple
pulseaudio-simpleA python wrapper for thepulseaudio simple API. Supports playing and recording audio via PulseAudio and PipeWire.This library is feature-complete, so there won't be much ongoing activity in this repository. Reported bugs will be fixed. PRs for improvements are always welcome.Dependencieslibpulse-simple.so.0(part oflibpulse0on Debian orlibpulseon Arch)A running PulseAudio/PipeWire serverThere's a good chance your Linux distribution comes with PulseAudio or PipeWire preinstalled.Installationpip3installpasimpleQuick startThere are two simple convenience functions for recording/playing audio to/from a.wavfile:frompasimpleimportrecord_wav,play_wav# Record 5 seconds of audio from the default recording devicerecord_wav('/tmp/test_recording.wav',5)# Play the recording via the default output deviceplay_wav('/tmp/test_recording.wav')Both functions block until all audio has been recorded/played. The default encoding used byrecord_wavisPA_SAMPLE_S24LE, mono, 41kHz. The functionplay_wavcan only recognize files encoded in one of the following formats:PA_SAMPLE_U8,PA_SAMPLE_S16LE,PA_SAMPLE_S24LE,PA_SAMPLE_S32LE. For more complex use cases, scroll down to the "Documentation" section.RecordingA more extensive example for recording audio can be found inexamples/record.py:importwaveimportpasimple# Audio attributes for the recordingFORMAT=pasimple.PA_SAMPLE_S32LESAMPLE_WIDTH=pasimple.format2width(FORMAT)CHANNELS=1SAMPLE_RATE=41000# Record 10 seconds of audiowithpasimple.PaSimple(pasimple.PA_STREAM_RECORD,FORMAT,CHANNELS,SAMPLE_RATE)aspa:audio_data=pa.read(CHANNELS*SAMPLE_RATE*SAMPLE_WIDTH*10)# Save audio to a filewithwave.open('recording.wav','wb')aswave_file:wave_file.setsampwidth(SAMPLE_WIDTH)wave_file.setnchannels(CHANNELS)wave_file.setframerate(SAMPLE_RATE)wave_file.writeframes(audio_data)In this example we're explicity specifying the audio format to be used for recording. When thePaSimpleobject is created, it opens a PulseAudio stream with the specified format. Further parameters that can be used in thePaSimpleconstructor are described in more detail under "Documentation" below.The recording starts as soon as thePaSimpleobject is created and audio data is buffered internally. Calls toreadcan retrieve the raw audio data, specifying the number of bytes to read as an argument. The function will block until the requested number of bytes is available. When done recording, thePaSimpleobject's audio stream should be closed with a call toclose(). Alternatively, it can be used with python's context manager (thewithstatement in the example above).Finally, the data is written to a.wavfile. We specify the audio format again, so that a correct.wavfile header can be written.PlayingAn example for playing audio can be found inexamples/play.py:importwaveimportpasimple# Read a .wav file with its attributeswithwave.open('recording.wav','rb')aswave_file:format=pasimple.width2format(wave_file.getsampwidth())channels=wave_file.getnchannels()sample_rate=wave_file.getframerate()audio_data=wave_file.readframes(wave_file.getnframes())# Play the file via PulseAudiowithpasimple.PaSimple(pasimple.PA_STREAM_PLAYBACK,format,channels,sample_rate)aspa:pa.write(audio_data)pa.drain()To play a.wavfile, we basically do the recording steps in reverse. First, we read the audio encoding together with the raw audio data from the file. When creating thePaSimpleobject, this time, we're opening a playback stream and specify the format of the audio we're going to play. It's then as simple as passing the raw audio data to thewritefunction. Finally, we calldrainto make sure all audio has played before closing the stream by leaving thewithcontext.StreamingAn annotated example of how to stream audio from/to a source/sink can be found inexamples/echo.pyDocumentationThis sections describes all constants/functions/classes available in thepasimplemodule.ConstantsStream directionsThe stream direction is used when creating aPaSimpleobject to specify whether the stream should be used for playing or recording audio.ConstantDescriptionPA_STREAM_PLAYBACKOpen a stream for playbackPA_STREAM_RECORDOpen a stream for recordingAudio formatsFormats that can be used with PulseAudio to play or record audio. PulseAudio's documentation for these formats can be foundhere.ConstantDescriptionPA_SAMPLE_U8Unsigned 8 Bit PCMPA_SAMPLE_ALAW8 Bit a-LawPA_SAMPLE_ULAW8 Bit mu-LawPA_SAMPLE_S16LESigned 16 Bit PCM, little endian (PC)PA_SAMPLE_S16BESigned 16 Bit PCM, big endianPA_SAMPLE_FLOAT32LE32 Bit IEEE floating point, little endian (PC), range -1.0 to 1.0PA_SAMPLE_FLOAT32BE32 Bit IEEE floating point, big endian, range -1.0 to 1.0PA_SAMPLE_S32LESigned 32 Bit PCM, little endian (PC)PA_SAMPLE_S32BESigned 32 Bit PCM, big endianPA_SAMPLE_S24LESigned 24 Bit PCM packed, little endian (PC)PA_SAMPLE_S24BESigned 24 Bit PCM packed, big endianPA_SAMPLE_S24_32LESigned 24 Bit PCM in LSB of 32 Bit words, little endian (PC)PA_SAMPLE_S24_32BESigned 24 Bit PCM in LSB of 32 Bit words, big endianConvenience functionswidth2format(sample_width)sample_width: Audio sample width to return a matching format for.Returns one ofPA_SAMPLE_U8,PA_SAMPLE_S16LE,PA_SAMPLE_S24LEorPA_SAMPLE_S32LE(common PCM audio formats), corresponding to the provided sample width or an error if none match.format2width(audio_format)audio_format: One of thePA_SAMPLE_*audio formats to return the width for.Returns the sample width for an audio format.play_wav(file_path)file_path: Path to a.wavfile to be played.Plays a.wavfile via PulseAudio and blocks until all audio data has been played. The following formats are supported:PA_SAMPLE_U8,PA_SAMPLE_S16LE,PA_SAMPLE_S24LE,PA_SAMPLE_S32LE. Throws awave.Errorif the.wavfile cannot be read or aPaSimpleErrorif the audio data cannot be played.record_wav(file_path,length,format=PA_SAMPLE_S24LE,channels=1,sample_rate=41000)file_path: Path to a.wavfile the recorded audio will be written to.length: The length of the recording in seconds.format: Audio format to be used for the recording (one ofPA_SAMPLE_U8,PA_SAMPLE_S16LE,PA_SAMPLE_S24LE,PA_SAMPLE_S32LE).channels: Number of channels to record (1=mono, 2=stereo).sample_rate: Sample rate for the recording in Hz.Records a.wavfile via PulseAudio and blocks until all audio data has been recorded. The following formats are supported:PA_SAMPLE_U8,PA_SAMPLE_S16LE,PA_SAMPLE_S24LE,PA_SAMPLE_S32LE. Throws awave.Errorif the.wavfile cannot be written or aPaSimpleErrorif the audio data cannot be recorded.PaSimpleAn instance ofPaSimplerepresents an audio stream for playing or recording audio via PulseAudio. On error, all functions throw aPaSimpleError.PaSimple(direction,format,channels,rate,app_name='python',stream_name=None,server_name=None,device_name=None,maxlength=-1,tlength=-1,prebuf=-1,minreq=-1,fragsize=-1):direction: EitherPA_STREAM_PLAYBACKorPA_STREAM_RECORD.format: The audio encoding (one ofPA_SAMPLE_*) for this stream.channels: Integer specifying the number of channels (1=mono, 2=stereo).rate: Integer specifying the sample rate in Hz.app_name: String specifying the name of the application that will be registered in PulseAudio.stream_name:None(useapp_name) or a string specifying the name of this stream that will be registered in PulseAudio.server_name:None(default) or a string specifying a PulseAudio server name.device_name:None(default) or a string specifying a specific PulseAudio device for recording or playback.maxlength:-1(default: max supported) or an integer specifying the buffer size limit in bytes.tlength:-1(default: about 2s) or an integer specifying how many bytes to keep in the playback buffer.prebuf:-1(usetlength) or an integer specifying how many bytes to buffer before starting playback.minreq:-1(default: about 2s) or an integer specifying the minimum size of chunks for refilling the playback buffer in bytes.fragsize:-1(default: about 2s) or an integer specifying the size of recording chunks in bytes.Initialize a PulseAudio simple API stream for playing or recording audio data.close()Close the underlying stream and free resources.direction()Returns the direction specified in the constructor.format()Returns the audio format specified in the constructor.channels()Returns the number of audio channels specified in the constructor.rate()Returns the audio rate specified in the constructor.read(num_bytes)num_bytes: The number of bytes to read.Record data from the PulseAudio server.PA_STREAM_RECORDmust have been used during initialization. This function blocks and returnsnum_bytesbytes of audio data.write(data)data: Raw audio data to be played.Play audio via the PulseAudio server.PA_STREAM_PLAYBACKmust have been used during initialization. Encoding ofdatamust match the one specified in the constructor.drain()Blocks until all remaining data in the buffer has been played.flush()Discards any data in the record/playback buffers.get_latency()Returns the record/playback latency reported by PulseAudio in microseconds.PulseAudio error codesThis list of PulseAudio internal error codes has beentaken from here.Error codeDescription0No error1Access failure2Unknown command3Invalid argument4Entity exists5No such entity6Connection refused7Protocol error8Timeout9No authentication key10Internal error11Connection terminated12Entity killed13Invalid server14Module initialization failed15Bad state16No data17Incompatible protocol version18Data too large19Operation not supported20The error code was unknown to the client21Extension does not exist22Obsolete functionality23Missing implementation24The caller forked without calling execve() and tried to reuse the context25An IO error happened26Device or resource busy27Not really an error but the first invalid error code