#!/usr/bin/python3 import asyncio import signal from contextlib import suppress import pulsectl_asyncio import time import subprocess #import pulsectl #print('Event types:', pulsectl.PulseEventTypeEnum) #print('Event facilities:', pulsectl.PulseEventFacilityEnum) #print('Event masks:', pulsectl.PulseEventMaskEnum) last_reload = 0 async def listen(): async with pulsectl_asyncio.PulseAsync('event-printer') as pulse: async for event in pulse.subscribe_events('all'): global last_reload if (event.facility == "sink_input" and event.index == 20 or event.facility == "server" and event.index == -1) and event.t == "change" and time.time() - last_reload >= 2: last_reload = time.time() subprocess.call(["pacmd", ".include", "/etc/pulse/default.pa.d/10-noise-cancellation.pa"]) async def main(): # Run listen() coroutine in task to allow cancelling it listen_task = asyncio.create_task(listen()) # register signal handlers to cancel listener when program is asked to terminate for sig in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT): loop.add_signal_handler(sig, listen_task.cancel) # Alternatively, the PulseAudio event subscription can be ended by breaking/returning from the `async for` loop with suppress(asyncio.CancelledError): await listen_task # Run event loop until main_task finishes loop = asyncio.get_event_loop() loop.run_until_complete(main())