You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js检测电脑播放的音频并自动生成歌曲信息文件

实现方案

核心思路

Windows 10 以上系统提供了 系统媒体传输控制(SMTC) 接口,所有符合规范的媒体播放器(包括Groove Music)都会将当前播放状态、媒体元数据同步到该接口,你只需要监听SMTC的播放状态变更事件,就能捕获到歌曲切换动作,无需对Groove Music做进程注入或Hook。

依赖安装

需要用到两个Node.js相关包,你也可以根据自己的使用习惯替换同类工具:

  • winrt-api:用于直接调用Windows Runtime原生API
  • fs-extra(可选,也可直接用Node.js原生fs模块):简化文件写入、目录创建操作
    安装命令:
npm install winrt-api fs-extra

核心代码实现

const { Windows } = require('winrt-api');
const fs = require('fs-extra');
const path = require('path');

// 存储上一首歌曲的唯一标识,避免同首歌重复生成文件
let lastSongUniqueId = '';
// 生成文件的存储目录,可自行修改
const OUTPUT_FOLDER = path.join(__dirname, 'played_song_records');

// 初始化输出目录,不存在则自动创建
fs.ensureDirSync(OUTPUT_FOLDER);

// 申请获取SMTC全局会话管理实例
const smtcManager = Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager.requestAsync().getResults();

// 监听全局媒体会话变更事件
smtcManager.addEventListener('currentsessionchanged', () => {
  const currentSession = smtcManager.getCurrentSession();
  // 过滤非Groove Music的播放会话,Groove的AppUserModelId为固定值
  if (!currentSession || currentSession.sourceAppUserModelId !== 'Microsoft.ZuneMusic_8wekyb3d8bbwe!Microsoft.ZuneMusic') {
    return;
  }

  // 监听当前会话的媒体属性变更事件,切歌时会触发该事件
  currentSession.addEventListener('mediapropertieschanged', async () => {
    const mediaProperties = await currentSession.tryGetMediaPropertiesAsync();
    if (!mediaProperties) return;

    const musicInfo = mediaProperties.musicProperties;
    // 生成当前歌曲的唯一标识
    const currentSongId = `${musicInfo.title}-${musicInfo.artist}-${musicInfo.album}`;
    const playbackStatus = currentSession.getPlaybackInfo().playbackStatus;

    // 仅当歌曲为新内容且处于播放状态时生成文件
    if (currentSongId !== lastSongUniqueId && playbackStatus === Windows.Media.Control.GlobalSystemMediaTransportControlsSessionPlaybackStatus.playing) {
      lastSongUniqueId = currentSongId;
      // 替换文件名中的Windows非法字符
      const safeFileName = `${musicInfo.title.replace(/[<>:"/\\|?*]/g, '_')}.txt`;
      const fileContent = `Song Name: ${musicInfo.title}
Artist Name: ${musicInfo.artist}
Album Name: ${musicInfo.album}`;
      // 写入目标文件
      await fs.writeFile(path.join(OUTPUT_FOLDER, safeFileName), fileContent, 'utf8');
    }
  });
});

注意事项

  • 代码仅支持Windows 10 1809及以上版本运行,低于该版本的系统未开放SMTC的JS调用权限
  • 如果需要开机自启,可以将脚本通过pkg等工具打包成exe后添加到Windows启动目录
  • 若后续需要适配其他播放器,仅需要修改过滤条件里的AppUserModelId即可

内容的提问来源于stack exchange,提问作者BIOLOGY SCIENCE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:06:03