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:
objecthttps://stackoverflow.com/a/20982715/185510
- 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:
- 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:
AudioDevice
- class pycaw.pycaw.AudioDevice(id, state, properties, dev)[source]
Bases:
objecthttps://stackoverflow.com/a/20982715/185510
- 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:
objecthttps://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 IconPath: str
Please, note that this returns an empty string if the client hadn’t called the setter method before.
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
Callbacks
- class pycaw.callbacks.AudioEndpointVolumeCallback(*args: Any, **kw: Any)[source]
Bases:
COMObjectCallback 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.EndpointVolumeAccess endpoint volume control interface
- 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.contentschannels (
int) – Number of audio channelschannel_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:
- class pycaw.callbacks.AudioSessionEvents(*args: Any, **kw: Any)[source]
Bases:
COMObjectCallback 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
AudioSessionRepresents 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:
- 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 channelsnew_channel_volume_array (
list[float]) – Per-channel volume levels in range [0.0, 1.0]. Length equals channel_countchanged_channel (
int) – Index of the channel whose volume changedevent_context (
Any) – GUID identifying who made the change. Access string representation via event_context.contents
- Return type:
- on_display_name_changed(new_display_name, event_context)[source]
Called when the audio session display name changes.
- on_grouping_param_changed(new_grouping_param, event_context)[source]
pycaw user interface
- Return type:
- 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.
- class pycaw.callbacks.AudioSessionNotification(*args: Any, **kw: Any)[source]
Bases:
COMObjectCallback 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:
Set COM to MTA mode before importing pycaw or comtypes:
import sys sys.coinit_flags = 0
Get the AudioSessionManager:
from pycaw.utils import AudioUtilities mgr = AudioUtilities.GetAudioSessionManager()
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)
Activate notifications by calling GetSessionEnumerator:
mgr.GetSessionEnumerator()
Unregister when finished:
mgr.UnregisterSessionNotification(callback)
See also
AudioUtilities.GetAudioSessionManagerGet the session manager instance
- 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:
- class pycaw.callbacks.MMNotificationClient(*args: Any, **kw: Any)[source]
Bases:
COMObjectCallback 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.GetDeviceEnumeratorGet the device enumerator
- DataFlow = ['eRender', 'eCapture', 'eAll', 'EDataFlow_enum_count']
- DeviceStates = {1: 'Active', 2: 'Disabled', 4: 'NotPresent', 8: 'Unplugged'}
- 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 coderole (
str) – Device role as string (e.g., “eConsole”, “eMultimedia”)role_id (
int) – Numeric role codedefault_device_id (
str|None) – Device ID of the new default device, or None when no endpoint is available for the role
- Return type:
- on_device_state_changed(device_id, new_state, new_state_id)[source]
Called when an audio endpoint device state changes.