import pyudev import os def detect_media(): # Create a context for monitoring context = pyudev.Context() # Define the subsystem to monitor subsystem = 'block' # Set the initial media count media_count = len(list(context.list_devices(subsystem=subsystem))) # Monitor for changes monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem=subsystem) for device in iter(monitor.poll, None): current_media_count = len(list(context.list_devices(subsystem=subsystem))) # Check if the media count has changed if current_media_count != media_count: # Play the sound based on whether media is plugged in or removed if current_media_count > media_count: # Sound when media is plugged in sound_file = "/usr/share/sounds/Yaru/stereo/device-added.oga" else: # Sound when media is removed sound_file = "/usr/share/sounds/Yaru/stereo/device-removed.oga" # Use the "aplay" command to play the sound file os.system(f"ogg123 {sound_file}") # Update the media count media_count = current_media_count if __name__ == "__main__": detect_media()