如何使用Python获取Windows 10中当前播放媒体的标题

11
每当Windows 10中播放音频时,无论是来自Spotify、Firefox还是游戏,当您调节音量时,Windows会在角落里显示歌曲艺术家、标题以及正在播放的应用程序,就像下面的照片一样(有时候,如果只有游戏正在发出声音,它只会显示正在播放声音的应用程序)。

enter image description here

我希望用Python获取那些数据。我的最终目标是,如果应用程序正在播放我不喜欢的内容(比如广告),将其静音。

你找到了吗,@Alexander? - RaduS
@Radus 我得到了窗口的瓷砖,而不是标题。标题通常显示类似于“Spotify.exe”的内容,当不播放媒体时,而当播放媒体时,它会显示歌曲名称。我将在此问题的答案中发布示例。 - Alexander
3个回答

26
原来可以直接使用Windows Runtime API(winrt)访问此信息,而无需使用解决方法。以下代码允许您使用Windows Runtime API的winrt包收集可用于Windows的媒体信息字典。它不依赖于窗口标题/应用程序名称的更改,而是依赖于winrt包装器。所有展示的代码都使用Python 3和通过pip安装的winrt库。
import asyncio

from winrt.windows.media.control import \
    GlobalSystemMediaTransportControlsSessionManager as MediaManager


async def get_media_info():
    sessions = await MediaManager.request_async()

    # This source_app_user_model_id check and if statement is optional
    # Use it if you want to only get a certain player/program's media
    # (e.g. only chrome.exe's media not any other program's).

    # To get the ID, use a breakpoint() to run sessions.get_current_session()
    # while the media you want to get is playing.
    # Then set TARGET_ID to the string this call returns.

    current_session = sessions.get_current_session()
    if current_session:  # there needs to be a media session running
        if current_session.source_app_user_model_id == TARGET_ID:
            info = await current_session.try_get_media_properties_async()

            # song_attr[0] != '_' ignores system attributes
            info_dict = {song_attr: info.__getattribute__(song_attr) for song_attr in dir(info) if song_attr[0] != '_'}

            # converts winrt vector to list
            info_dict['genres'] = list(info_dict['genres'])

            return info_dict

    # It could be possible to select a program from a list of current
    # available ones. I just haven't implemented this here for my use case.
    # See references for more information.
    raise Exception('TARGET_PROGRAM is not the current media session')


if __name__ == '__main__':
    current_media_info = asyncio.run(get_media_info())

current_media_info将是以下格式的字典,然后可以根据需要在程序中访问信息:

{
    'album_artist': str,
    'album_title': str,
    'album_track_count': int, 
    'artist': str,
    'genres': list,
    'playback_type': int,
    'subtitle': str, 
    'thumbnail': 
        <_winrt_Windows_Storage_Streams.IRandomAccessStreamReference object at ?>, 
    'title': str,
    'track_number': int,
}

控制媒体

如OP所说,他们的最终目标是控制媒体,使用相同的库应该是可行的。 可能需要参考以下链接了解更多信息(在我的情况下不需要):

(获取媒体缩略图)

实际上也可以“抓取”正在播放的媒体的专辑艺术/媒体缩略图(显示在OP截图的右侧),尽管OP没有要求,但可能有人想要这样做:

from winrt.windows.storage.streams import \
    DataReader, Buffer, InputStreamOptions


async def read_stream_into_buffer(stream_ref, buffer):
    readable_stream = await stream_ref.open_read_async()
    readable_stream.read_async(buffer, buffer.capacity, InputStreamOptions.READ_AHEAD)


# create the current_media_info dict with the earlier code first
thumb_stream_ref = current_media_info['thumbnail']

# 5MB (5 million byte) buffer - thumbnail unlikely to be larger
thumb_read_buffer = Buffer(5000000)

# copies data from data stream reference into buffer created above
asyncio.run(read_stream_into_buffer(thumb_stream_ref, thumb_read_buffer))

# reads data (as bytes) from buffer
buffer_reader = DataReader.from_buffer(thumb_read_buffer)
byte_buffer = buffer_reader.read_bytes(thumb_read_buffer.length)

with open('media_thumb.jpg', 'wb+') as fobj:
    fobj.write(bytearray(byte_buffer))

这将保存media_thumb.jpg到当前工作目录(cwd),然后可以在其他地方使用。

文档和参考:

可能从多个可用的媒体流中选择?

请注意,我还没有测试或尝试过这个,只是为那些想要实验的人提供一个指针:

与当前使用方式相反


2
根据此处的答案:https://dev59.com/EMLra4cB1Zd3GeqPJ3Uq,自 Python 3.10.0 起,您必须使用 winsdk 模块替换 winrt 模块。此外,这应该是被选中的答案。回答者正在回答原始问题,使用 Windows 运行时 API,而不是以裸方式使用 Win32 API 来捕获运行播放器的窗口标题。 - digfish

3

我正在获取窗口标题以获取歌曲信息。通常,应用程序名称会显示在标题中,但当播放歌曲时,会显示歌曲名称。这里有一个函数,返回所有窗口标题的列表。

from __future__ import print_function
import ctypes
def get_titles(): 
    EnumWindows = ctypes.windll.user32.EnumWindows
    EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
    GetWindowText = ctypes.windll.user32.GetWindowTextW
    GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
    IsWindowVisible = ctypes.windll.user32.IsWindowVisible
    
    titles = []
    def foreach_window(hwnd, lParam):
        if IsWindowVisible(hwnd):
            length = GetWindowTextLength(hwnd)
            buff = ctypes.create_unicode_buffer(length + 1)
            GetWindowText(hwnd, buff, length + 1)
            titles.append(buff.value)
        return True
    EnumWindows(EnumWindowsProc(foreach_window), 0)
    return titles

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接