Skip to content

Initialization & Cleanup

Jan Janak edited this page Jan 28, 2021 · 10 revisions

Initialization

To initialize the client, import the class PulseAudio, create a new instance, and invoke the method connect to connect to the PulseAudio server:

import { PulseAudio } from 'pulseaudio.js';

const pa = new PulseAudio("Test client for pulseaudio.js");
await pa.connect();

The string argument passed to the constructor is a human-friendly name identifying the client. The client will connect to the PulseAudio server via the server's native UNIX domain socket interface (/run/user/<uid>/pulse/native by default). The client will attempt to load a PulseAudio authentication cookie from ~/.config/pulse/cookie and if found, it will use the cookie to authenticate to the PulseAudio server.

The client library uses the debug package for debugging messages. To see the messages, enable the pa:* namespaces by setting the environment variable DEBUG before starting NodeJS:

DEBUG="pa:*" node index.js
pa:client Connecting to PulseAudio via '/run/user/1000/pulse/native' +0ms
pa:client Trying to load PulseAudio authentication cookie from '/home/janakj/.config/pulse/cookie' +5ms
pa:client Connected to pulseaudio 13.99.2 speaking native protocol versions <= 34 +5ms

Reconnect

The client does not attempt to automatically reconnect to the PulseAudio server when disconnected, for example, when the server crashes or is shut down. This is left to the application since reconnecting to the PulseAudio server usually requires re-initialization of the resources previously created by the application. The client object implements the EventEmitter interface and emits an error event when disconnected from PulseAudio server.

Cleanup

When the client is no longer needed, call the method disconnect to disconnect from the PulseAudio server:

await pa.disconnect();

Note that the method disconnect does not automatically release resources created by the client on the PulseAudio server. These can include loaded modules, virtual sources and sinks, and sample cache files. For a clean shutdown, the client should release its resources manually before calling disconnect.

PulseAudio server allows the client to attach arbitrary key-value attributes to any resource. Thus, one way for the client to keep track of what resources need to be destroyed is with a custom attribute attached to each resource created by the client. To handle crashes and restarts, the client could then remove and recreate all such resources when starting up.