python - 如何使用 python 在 Windows 10 中获取当前正在播放的媒体的标题
问题描述
每当在 Windows 10 中播放音频时,无论是来自 Spotify、Firefox 还是游戏。当您打开音量时,窗口的角落会显示歌曲艺术家、标题和正在播放的应用程序,如下图所示(有时它只显示游戏正在播放声音时哪个应用程序正在播放声音)
我想以某种方式用 python 获取这些数据。我的最终目标是,如果某个应用程序正在播放我不喜欢的内容(例如广告),则将其静音。
解决方案
事实证明,如果没有解决方法,并且通过使用Windows 运行时 API ( )直接访问此信息,这是可能的winrt
。
显示的所有代码都使用 Python 3 和winrt
通过 pip 安装的库
收集媒体/“正在播放”信息
以下代码允许您使用 Windows 运行时 API 的 winrt 包装器收集可供 Windows 使用的媒体信息字典。它不像此处的其他答案那样依赖于窗口的标题/应用程序名称的更改。
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 所说,他们的最终目标是控制媒体,这应该可以使用相同的库。请参阅此处以获取更多信息(在我的情况下我不需要这个):
- Microsoft WinRT Docs - Windows.Media.Control - GlobalSystemMediaTransportControlsSession 类
(例如
await current_session.try_pause_async()
)
(获取媒体缩略图)
事实上,也可以“刮掉”当前正在播放的媒体的专辑封面/媒体缩略图(显示在 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))
这会将 a 保存media_thumb.jpg
到当前工作目录(cwd),然后可以在其他地方使用它。
文档和参考:
- Stackoverflow - 这个 Python 答案的主要“灵感”;最初在 C# 中
- Github xlang - 将 Windows RT API 与 xlang 和 Python 一起使用
- Github xlang - IAsync* 接口方法的异步使用
- Microsoft WinRT 文档 - Windows.Media.Control - TryGetMediaPropertiesAsync()
- Microsoft WinRT Docs - Windows.Storage.Streams - IBuffer 接口
可能从多个可用的媒体流中选择?
请注意,我没有测试或尝试过这个,这只是给任何想要尝试的人的一个指针:
- Microsoft WinRT Docs - Windows.Media.Control - GetSessions()
(可以通过
sessions.get_sessions()
上面访问)
与目前使用的
- Microsoft WinRT Docs - Windows.Media.Control - GetCurrentSession()
(通过
sessions.get_current_session()
上述方式访问)
推荐阅读
- esp32 - 如何修复“大师冥想错误:核心 1 恐慌”(LoadProhibited)。由 registerForNotify() 引起的异常未处理
- javascript - Javascript 在函数执行后显示更多/更少的问题
- scala - 如何使我的排序函数尾递归?
- javascript - fetch API:只有在 POST 表单中没有错误时才重定向
- linux - 如何将一个查询的结果连接到另一个查询
- asp.net-mvc - 我的下拉菜单在 mvc 中的编辑模式上没有获得价值
- c++ - 最佳实践:函数内频繁使用大时间缓冲区 (C++)
- php - PHP DOMDocument Html 表到 XML
- python-3.x - 如何从文本文件中提取多个圣经经文?
- c# - 一般将孩子添加到父母