如何使用 python 在 Windows 10 中获取当前正在播放的媒体的标题 [英] How can I get the title of the currently playing media in windows 10 with python

查看:23
本文介绍了如何使用 python 在 Windows 10 中获取当前正在播放的媒体的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论何时在 Windows 10 中播放音频,无论是来自 Spotify、Firefox 还是游戏.当你打开音量时,windows 的角落里会显示歌曲艺术家、标题以及正在播放的应用程序,如下图所示(有时它只显示游戏正在播放声音时哪个应用程序正在播放声音)

Whenever audio is playing in windows 10, whether it is from Spotify, Firefox, or a game. When you turn the volume, windows has a thing in the corner that says the song artist, title, and what app is playing like the photo below (sometimes it only says what app is playing sound if a game is playing the sound)

我想以某种方式使用 python 获取这些数据.我的最终目标是,如果应用程序正在播放我不喜欢的内容(例如广告),则将其静音.

I want to somehow get that data with python. My end goal, is to mute an application if it is playing something I don't like, such as an advertisement.

推荐答案

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

I am getting the titles of the windows to get the song information. Usually, the application name is displayed in the title, but when it is playing a song, the song name is shown. Here is a function that returns a list of all the window titles.

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

这篇关于如何使用 python 在 Windows 10 中获取当前正在播放的媒体的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆