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]
static GetAllDevices(data_flow=2, device_state=15)[source]
static GetAllSessions()[source]
static GetAudioSessionManager()[source]
static GetDeviceEnumerator()[source]

Get an instance of IMMDeviceEnumerator.

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

Get data flow information of a given endpoint.

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

  • outputType (int, optional) – 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

static GetProcessSession(id)[source]
static GetSpeakers()[source]

get the speakers (1st render + multimedia) device

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

AudioDevice

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

Bases: object

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

property AudioSessionManager
property EndpointVolume
property FriendlyName

AudioSession

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

Bases: object

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

property DisplayName

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

property GroupingParam
property IconPath

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

property Identifier
property InstanceIdentifier
property Process
property ProcessId
property SimpleAudioVolume
property State
channelAudioVolume()[source]
register_notification(callback)[source]
unregister_notification()[source]

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, **kw)[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

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 (comtypes.GUID) – GUID identifying who made the change. Access string representation via event_context.contents

  • channels (int) – Number of audio channels

  • channel_volumes (list of 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

class pycaw.callbacks.AudioSessionEvents(*args, **kw)[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]
OnDisplayNameChanged(new_display_name, event_context)[source]
OnGroupingParamChanged(new_grouping_param, event_context)[source]
OnIconPathChanged(new_icon_path, event_context)[source]
OnSessionDisconnected(disconnect_reason_id)[source]
OnSimpleVolumeChanged(new_volume, new_mute, event_context)[source]
OnStateChanged(new_state_id)[source]
on_channel_volume_changed(channel_count, new_channel_volume_array, changed_channel, event_context)[source]

pycaw user interface

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 (comtypes.GUID) – GUID identifying who made the change. Access string representation via event_context.contents

on_grouping_param_changed(new_grouping_param, event_context)[source]

pycaw user interface

on_icon_path_changed(new_icon_path, event_context)[source]

pycaw user interface

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

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 (comtypes.GUID) – GUID identifying who made the change. Access string representation via event_context.contents

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)

class pycaw.callbacks.AudioSessionNotification(*args, **kw)[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]
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

class pycaw.callbacks.MMNotificationClient(*args, **kw)[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]
OnDeviceAdded(added_device_id)[source]
OnDeviceRemoved(removed_device_id)[source]
OnDeviceStateChanged(device_id, new_state_id)[source]
OnPropertyValueChanged(device_id, property_struct)[source]
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) – Device ID of the new default device

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

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

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)

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 (pycaw.api.mmdeviceapi.depend.structures.PROPERTYKEY) – Structure containing the property GUID and PID

  • fmtid (comtypes.GUID) – GUID of the changed property

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