I’m tying to create a script that retrieves information about currently playing media on Windows using the Windows Media Control API.
The script uses asyncio
for asynchronous operations and the win32more
library to interact with the Windows Media Control API.
This is my code:
import asyncio
import pythoncom
import logging
from win32more.Windows.Media.Control import (
GlobalSystemMediaTransportControlsSessionManager as MediaManager,
)
# Configure logging
logging.basicConfig(
level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s"
)
async def get_media_info():
logging.debug("Requesting media session manager...")
sessions = await MediaManager.RequestAsync()
current_session = sessions.GetCurrentSession()
if current_session:
current_id = current_session.SourceAppUserModelId
logging.info(f"Current session ID: {current_id}")
try:
info = await current_session.TryGetMediaPropertiesAsync()
info_dict = {
"SourceAppUserModelId": current_id,
"Title": info.Title,
"Artist": info.Artist,
"AlbumTitle": info.AlbumTitle,
"PlaybackStatus": current_session.GetPlaybackInfo().PlaybackStatus,
}
return info_dict
except Exception as e:
logging.error(f"Error getting info for current session: {e}")
else:
logging.warning("No current media session found.")
return None
async def list_all_sessions():
logging.debug("Requesting all available sessions...")
sessions = await MediaManager.RequestAsync()
all_sessions = sessions.GetSessions()
logging.info("All available session IDs:")
for session in all_sessions:
logging.info(f"Session ID: {session.SourceAppUserModelId}")
async def main():
try:
# fix for "An error occurred: [WinError -2147221008] CoInitialize has not been called"
logging.debug("Initializing COM library...")
pythoncom.CoInitialize()
await list_all_sessions()
media_info = await get_media_info()
if media_info:
logging.info("Current media session info:")
for key, value in media_info.items():
logging.info(f"{key}: {value}")
except Exception as e:
logging.error(f"An error occurred: {e}")
finally:
logging.debug("Uninitializing COM library...")
pythoncom.CoUninitialize()
if __name__ == "__main__":
asyncio.run(main())
But it seems to get stuck on await MediaManager.RequestAsync()
, as this is the output:
PS C:UsersedoarDocumentsworknotnotch> python media_info.py
2024-08-10 09:49:53,757 - DEBUG - Using proactor: IocpProactor
2024-08-10 09:49:53,758 - DEBUG - Initializing COM library...
2024-08-10 09:49:53,759 - DEBUG - Requesting all available sessions...
|
Environment
- Python version:
3.12.3
- Operating System:
Windows 11 23H2
I cheked also this question How can I get the title of the currently playing media in windows 10 with python but I didn’t find the solution there.
Am I doing something wrong? Is there something I’m missing?
Any insights or suggestions would be greatly appreciated!