API Reference

This section documents the Pycaw API.

High-Level API

These classes provide the main interface for working with audio devices and sessions.

AudioUtilities

class pycaw.pycaw.AudioUtilities[source]

Bases: object

https://stackoverflow.com/a/20982715/185510

static CreateDevice(dev)[source]
Return type:

AudioDevice | None

static GetAllDevices(data_flow=2, device_state=15)[source]
Return type:

list[AudioDevice]

static GetAllSessions()[source]
Return type:

list[AudioSession]

static GetAudioSessionManager()[source]
Return type:

Any

static GetDeviceEnumerator()[source]

Get an instance of IMMDeviceEnumerator.

Return type:

Any

static GetEndpointDataFlow(devId, outputType=0)[source]

Get data flow information of a given endpoint.

Overloads:
  • devId (str), outputType (Literal[0]) → str

  • devId (str), outputType (Literal[1]) → int

  • devId (str), outputType (int) → str | int

Parameters:
  • devId (str) – ID of the device to query

  • outputType (int) – Output format: 0 (default) returns text representation, 1 returns numeric code

Returns:

Data flow direction. If outputType=0, returns one of: “eRender”, “eCapture”, “eAll”, “EDataFlow_enum_count”. If outputType=1, returns the numeric value (0-3).

Return type:

str or int

static GetMicrophone()[source]

get the microphone (1st capture + multimedia) device

Return type:

Any

static GetProcessSession(id)[source]
Return type:

AudioSession | None

static GetSpeakers()[source]

get the speakers (1st render + multimedia) device

Return type:

AudioDevice | None

static SetDefaultDevice(devId, roles=None)[source]
Return type:

None

AudioDevice

class pycaw.pycaw.AudioDevice(id, state, properties, dev)[source]

Bases: object

https://stackoverflow.com/a/20982715/185510

property AudioSessionManager: Any
property EndpointVolume: Any
property FriendlyName: str | None
property volume_percent: float

Master volume of this device as a percentage (0.0-100.0), the same scale the Windows volume mixer shows.

Convenience wrapper around GetMasterVolumeLevelScalar() / SetMasterVolumeLevelScalar(), so users don’t reach for the decibel based SetMasterVolumeLevel() by mistake. The setter clamps the value to the 0-100 range.

AudioSession

class pycaw.pycaw.AudioSession(audio_session_control2)[source]

Bases: object

https://stackoverflow.com/a/20982715/185510

property DisplayName: str

Please, note that this returns an empty string if the client hadn’t called the setter method before.

property GroupingParam: Any
property IconPath: str

Please, note that this returns an empty string if the client hadn’t called the setter method before.

property Identifier: str
property InstanceIdentifier: str
property Process: Process | None

Return the session’s process, or None when it has no process.

The special Windows System Sounds session has process ID 0, so it does not have an associated psutil.Process.

property ProcessId: int
property SimpleAudioVolume: Any
property State: int
channelAudioVolume()[source]
Return type:

Any

register_notification(callback)[source]
Return type:

None

unregister_notification()[source]
Return type:

None

Constants and Enums

class pycaw.constants.AUDCLNT_SHAREMODE(*values)[source]

Bases: Enum

AUDCLNT_SHAREMODE_EXCLUSIVE = 1
AUDCLNT_SHAREMODE_SHARED = 0
class pycaw.constants.AudioDeviceState(*values)[source]

Bases: Enum

Active = 1
Disabled = 2
NotPresent = 4
Unplugged = 8
class pycaw.constants.AudioSessionState(*values)[source]

Bases: IntEnum

Active = 1
Expired = 2
Inactive = 0
class pycaw.constants.DEVICE_STATE(*values)[source]

Bases: Enum

ACTIVE = 1
DISABLED = 2
MASK_ALL = 15
NOTPRESENT = 4
UNPLUGGED = 8
class pycaw.constants.EDataFlow(*values)[source]

Bases: Enum

EDataFlow_enum_count = 3
eAll = 2
eCapture = 1
eRender = 0
class pycaw.constants.ERole(*values)[source]

Bases: Enum

ERole_enum_count = 3
eCommunications = 2
eConsole = 0
eMultimedia = 1
class pycaw.constants.STGM(*values)[source]

Bases: Enum

STGM_READ = 0

Callbacks

class pycaw.callbacks.AudioEndpointVolumeCallback(*args: Any, **kw: Any)[source]

Bases: COMObject

Callback handler for audio endpoint (device) volume changes.

Subclass this class and override the on_notify method to handle notifications when an audio device’s volume or mute state changes.

Examples

Monitor the default audio device for volume changes:

class DeviceVolumeMonitor(AudioEndpointVolumeCallback):
    def on_notify(self, new_volume, new_mute, event_context,
                  channels, channel_volumes):
        print(f"Device volume: {new_volume:.2f}, muted: {new_mute}")

device = AudioUtilities.GetSpeakers()
callback = DeviceVolumeMonitor()
device.EndpointVolume.RegisterControlChangeNotify(callback)

See also

AudioDevice.EndpointVolume

Access endpoint volume control interface

OnNotify(pNotify)[source]

Fired by Windows, when the audio device volume/mute changed

Return type:

None

on_notify(new_volume, new_mute, event_context, channels, channel_volumes)[source]

Called when the audio endpoint volume or mute state changes.

Override this method in your subclass to handle volume change notifications.

Parameters:
  • new_volume (float) – Master volume level in range [0.0, 1.0]

  • new_mute (int) – Mute state: 0 (unmuted) or 1 (muted)

  • event_context (Any) – GUID identifying who made the change. Access string representation via event_context.contents

  • channels (int) – Number of audio channels

  • channel_volumes (list[float]) – Per-channel volume levels in range [0.0, 1.0]. Length equals the channels parameter

Raises:

NotImplementedError – This base implementation must be overridden in subclasses

Return type:

None

class pycaw.callbacks.AudioSessionEvents(*args: Any, **kw: Any)[source]

Bases: COMObject

Callback handler for audio session state and property changes.

Subclass this class and override any of the callback methods to handle specific events related to an audio session’s state, volume, or properties.

Examples

Create a custom callback to monitor session volume changes:

class VolumeMonitor(AudioSessionEvents):
    def on_simple_volume_changed(self, new_volume, new_mute, event_context):
        mute_str = "muted" if new_mute else "unmuted"
        print(f"Volume changed: {new_volume:.2f}, {mute_str}")

See also

AudioSession

Represents an audio session that can be monitored

AudioSessionDisconnectReason = ('DeviceRemoval', 'ServerShutdown', 'FormatChanged', 'SessionLogoff', 'SessionDisconnected', 'ExclusiveModeOverride')
AudioSessionState = ('Inactive', 'Active', 'Expired')
OnChannelVolumeChanged(channel_count, new_channel_volume_array, changed_channel, event_context)[source]
Return type:

None

OnDisplayNameChanged(new_display_name, event_context)[source]
Return type:

None

OnGroupingParamChanged(new_grouping_param, event_context)[source]
Return type:

None

OnIconPathChanged(new_icon_path, event_context)[source]
Return type:

None

OnSessionDisconnected(disconnect_reason_id)[source]
Return type:

None

OnSimpleVolumeChanged(new_volume, new_mute, event_context)[source]
Return type:

None

OnStateChanged(new_state_id)[source]
Return type:

None

on_channel_volume_changed(channel_count, new_channel_volume_array, changed_channel, event_context)[source]

Called when an audio session channel volume changes.

Parameters:
  • channel_count (int) – Number of audio channels

  • new_channel_volume_array (list[float]) – Per-channel volume levels in range [0.0, 1.0]. Length equals channel_count

  • changed_channel (int) – Index of the channel whose volume changed

  • event_context (Any) – GUID identifying who made the change. Access string representation via event_context.contents

Return type:

None

on_display_name_changed(new_display_name, event_context)[source]

Called when the audio session display name changes.

Parameters:
  • new_display_name (str) – The new display name for the audio session

  • event_context (Any) – GUID identifying who made the change. Access string representation via event_context.contents

Return type:

None

on_grouping_param_changed(new_grouping_param, event_context)[source]

pycaw user interface

Return type:

None

on_icon_path_changed(new_icon_path, event_context)[source]

pycaw user interface

Return type:

None

on_session_disconnected(disconnect_reason, disconnect_reason_id)[source]

Called when the audio session is disconnected.

Note: In most cases, you should use on_state_changed with state “Expired” instead, as it provides more reliable notification.

Parameters:
  • disconnect_reason (str) – Reason for disconnection as string (see AudioSessionDisconnectReason)

  • disconnect_reason_id (int) – Numeric disconnect reason code

Return type:

None

on_simple_volume_changed(new_volume, new_mute, event_context)[source]

Called when the audio session volume or mute state changes.

Parameters:
  • new_volume (float) – New master volume level in range [0.0, 1.0]

  • new_mute (int) – Mute state: 0 (unmuted) or 1 (muted)

  • event_context (Any) – GUID identifying who made the change. Access string representation via event_context.contents

Return type:

None

on_state_changed(new_state, new_state_id)[source]

Called when the audio session state changes.

Parameters:
  • new_state (str) – New state as string: “Inactive”, “Active”, or “Expired”

  • new_state_id (int) – Numeric state code: 0 (Inactive), 1 (Active), or 2 (Expired)

Return type:

None

class pycaw.callbacks.AudioSessionNotification(*args: Any, **kw: Any)[source]

Bases: COMObject

Callback handler for audio session creation events.

To use this class, subclass it and override the on_session_created method.

Notes

AudioSessionNotification requires Multi-Threaded Apartment (MTA) COM initialization. Follow these steps:

  1. Set COM to MTA mode before importing pycaw or comtypes:

    import sys
    sys.coinit_flags = 0
    
  2. Get the AudioSessionManager:

    from pycaw.utils import AudioUtilities
    mgr = AudioUtilities.GetAudioSessionManager()
    
  3. Create and register your callback subclass:

    class MyCallback(AudioSessionNotification):
        def on_session_created(self, new_session):
            print(f"New session created: {new_session}")
    
    callback = MyCallback()
    mgr.RegisterSessionNotification(callback)
    
  4. Activate notifications by calling GetSessionEnumerator:

    mgr.GetSessionEnumerator()
    
  5. Unregister when finished:

    mgr.UnregisterSessionNotification(callback)
    

See also

AudioUtilities.GetAudioSessionManager

Get the session manager instance

OnSessionCreated(new_session)[source]
Return type:

None

on_session_created(new_session)[source]

Called when a new audio session is created.

Override this method in your subclass to handle session creation events.

Parameters:

new_session (AudioSession) – The newly created audio session object

Raises:

NotImplementedError – This base implementation must be overridden in subclasses

Return type:

None

class pycaw.callbacks.MMNotificationClient(*args: Any, **kw: Any)[source]

Bases: COMObject

Callback handler for audio endpoint device events.

Subclass this class and override any callback methods to handle events such as device addition, removal, state changes, or default device changes.

Examples

Monitor for device additions and removals:

class DeviceMonitor(MMNotificationClient):
    def on_device_added(self, added_device_id):
        print(f"Device added: {added_device_id}")

    def on_device_removed(self, removed_device_id):
        print(f"Device removed: {removed_device_id}")

enumerator = AudioUtilities.GetDeviceEnumerator()
monitor = DeviceMonitor()
enumerator.RegisterEndpointNotificationCallback(monitor)

See also

AudioUtilities.GetDeviceEnumerator

Get the device enumerator

DataFlow = ['eRender', 'eCapture', 'eAll', 'EDataFlow_enum_count']
DeviceStates = {1: 'Active', 2: 'Disabled', 4: 'NotPresent', 8: 'Unplugged'}
OnDefaultDeviceChanged(flow_id, role_id, default_device_id)[source]
Return type:

None

OnDeviceAdded(added_device_id)[source]
Return type:

None

OnDeviceRemoved(removed_device_id)[source]
Return type:

None

OnDeviceStateChanged(device_id, new_state_id)[source]
Return type:

None

OnPropertyValueChanged(device_id, property_struct)[source]
Return type:

None

Roles = ['eConsole', 'eMultimedia', 'eCommunications', 'ERole_enum_count']
on_default_device_changed(flow, flow_id, role, role_id, default_device_id)[source]

Called when the default audio device for a role changes.

Parameters:
  • flow (str) – Data flow direction as string (e.g., “eRender”, “eCapture”)

  • flow_id (int) – Numeric data flow direction code

  • role (str) – Device role as string (e.g., “eConsole”, “eMultimedia”)

  • role_id (int) – Numeric role code

  • default_device_id (str | None) – Device ID of the new default device, or None when no endpoint is available for the role

Return type:

None

on_device_added(added_device_id)[source]

Called when a new audio endpoint device is added.

Parameters:

added_device_id (str) – Device ID of the newly added device

Return type:

None

on_device_removed(removed_device_id)[source]

Called when an audio endpoint device is removed.

Parameters:

removed_device_id (str) – Device ID of the removed device

Return type:

None

on_device_state_changed(device_id, new_state, new_state_id)[source]

Called when an audio endpoint device state changes.

Parameters:
  • device_id (str) – Device ID of the device that changed state

  • new_state (str) – New state as string (e.g., “Active”, “Disabled”, “NotPresent”)

  • new_state_id (int) – Numeric state code (see DeviceStates class attribute)

Return type:

None

on_property_value_changed(device_id, property_struct, fmtid, pid)[source]

Called when a device property value changes.

Parameters:
  • device_id (str) – Device ID of the device with changed property

  • property_struct (PROPERTYKEY) – Structure containing the property GUID and PID

  • fmtid (Any) – GUID of the changed property

  • pid (int) – Property identifier (PID) of the changed property

Return type:

None