pythonwindows-runtime

Getting current elapsed time of a song currently playing on Windows (Python)


I'm writing a program that requires the information about the song name, author(s) and the current elapsed time of the song. Song name and authors I can get with Windows' API (WinRT, more specifically winrt.windows.media.control, but I cannot find any way to retrieve the information about the current elapsed time.

The songs are being played from streaming services' apss, such as Spotify for Desktop, Apple Music app, etc.

The program's task is to play a pre-defined animation, synchronized with the song, that's why I need to have the elapsed time of the song.

I've tried "simulating" the elapsed time by detecting if the song has changed, and then resetting the timer. That has a major flaw, where if a song stops the timer still goes (because the API still shows the song as playing), so I'm unable to see whether the song is paused or not.

Recently I've also tried to make a little library that records audio samples from the microphone and sends them to Shazam. That works better, but it seems that the data of the elapsed time I get from it isn't that reliable.


Solution

  • After some time experimenting I've discovered a way to do this. Python's winrt binding library exposes the GlobalSystemMediaTransportControlsSessionManager, after getting the current session you can call get_timeline_properties(), which in turn will give you a GlobalSystemMediaTransportControlsSessionTimelineProperties object, that exposes a couple of useful attributes, including the current position of a playing track. Some credit goes to this question.

    So, assuming current_session from the linked question, a simple one-liner to get the position is:
    current_session.get_timeline_properties().position.seconds

    Note: It seems it likes to lag for about 2 seconds behind the actual track, and there's no finer resolution, only full seconds are supported it seems.