Skip to content

Instantly share code, notes, and snippets.

@shinagaki
Created July 20, 2026 15:47
Show Gist options
  • Select an option

  • Save shinagaki/f555c30862a6e10f625c5b98f136be6e to your computer and use it in GitHub Desktop.

Select an option

Save shinagaki/f555c30862a6e10f625c5b98f136be6e to your computer and use it in GitHub Desktop.
Windowsで数分おきに鳴る謎の通知音を追跡する3本のスクリプト(WASAPI / PulseAudio / wsl.exe起動監視)

Windowsで鳴る謎の音を追跡する3本のスクリプト

Windows PC から数分おきに鳴る、正体不明の通知音を追いかけるために書いたスクリプトです。 「どのプロセスが音を鳴らしたか」を、Windows 側と WSL 側の両方から記録します。

解説記事: https://creco.net/windows-mystery-notification-sound-wsl/

各スクリプトの役割

スクリプト 実行場所 役割
audio-source-logger.ps1 Windows WASAPI (Core Audio API) で、音を鳴らしたプロセス名・実行ファイル・PID を記録
wsl-audio-source-logger.sh WSL PulseAudio の再生ストリーム (sink-input) を監視し、WSL 側の音源と親プロセスを記録
watch-wsl-launcher.ps1 Windows wsl.exe / bash.exe の起動を検出し、起動元を親プロセスまで遡って記録

いずれも管理者権限は不要です。ログをファイルに書きながら常駐するので、音が鳴るまで放置して、あとからログを見る使い方を想定しています。停止は Ctrl + C。

使い方

# Windows 側(PowerShell)
powershell -ExecutionPolicy Bypass -File .\audio-source-logger.ps1

# wsl.exe の起動元を調べたいとき
powershell -ExecutionPolicy Bypass -File .\watch-wsl-launcher.ps1
# WSL 側
sudo apt install -y pulseaudio-utils   # pactl が無ければ
bash ./wsl-audio-source-logger.sh

ライセンス

MIT

<#
================================================================
audio-source-logger.ps1
どのアプリが音を鳴らしたかを時刻つきで記録するスクリプト
使い方:
powershell -ExecutionPolicy Bypass -File "<このファイルのパス>"
音が鳴るまで放置する。停止は Ctrl + C。
仕組み:
Windows Core Audio API (WASAPI) で、すべての再生デバイスの
オーディオセッションのピークレベルを 0.1 秒ごとに監視する。
レベルがしきい値を超えたセッションのプロセス名・実行ファイルパス・
時刻を記録する。Windows のシステム音(USB接続音・通知音など)も
「システム音」として個別に検出できる。
COM の呼び出しは PowerShell では正しく解決されないため、
すべて C# 側 (Add-Type) で実装している。
================================================================
#>
param(
[double]$Threshold = 0.0008, # このレベルを超えたら「音が鳴った」と判定 (0.0-1.0)
[int] $PollMs = 100, # 監視間隔(ミリ秒)
[int] $RefreshSec = 3, # セッション一覧を取り直す間隔(秒)
[double]$SilenceSec = 1.5, # 無音がこの秒数続いたら鳴り終わりと判定
[string]$LogPath = "" # ログ出力先(未指定ならスクリプトと同じ場所)
)
if ([string]::IsNullOrWhiteSpace($LogPath)) {
$baseDir = if ($PSScriptRoot) { $PSScriptRoot } else { [Environment]::GetFolderPath('Desktop') }
$LogPath = Join-Path $baseDir 'audio-source-log.txt'
}
# ===============================================================
# C# 側: Core Audio (WASAPI) のインターフェイス定義と列挙処理
# ===============================================================
$csharp = @'
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace AudioSpy
{
[ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDeviceEnumerator
{
[PreserveSig] int EnumAudioEndpoints(int dataFlow, int dwStateMask, out IMMDeviceCollection ppDevices);
[PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice ppEndpoint);
[PreserveSig] int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string pwstrId, out IMMDevice ppDevice);
[PreserveSig] int RegisterEndpointNotificationCallback(IntPtr pClient);
[PreserveSig] int UnregisterEndpointNotificationCallback(IntPtr pClient);
}
[ComImport, Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDeviceCollection
{
[PreserveSig] int GetCount(out int pcDevices);
[PreserveSig] int Item(int nDevice, out IMMDevice ppDevice);
}
[ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMDevice
{
[PreserveSig] int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams,
[MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);
[PreserveSig] int OpenPropertyStore(int stgmAccess, out IPropertyStore ppProperties);
[PreserveSig] int GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppstrId);
[PreserveSig] int GetState(out int pdwState);
}
[StructLayout(LayoutKind.Sequential)]
public struct PropertyKey { public Guid fmtid; public int pid; }
[StructLayout(LayoutKind.Explicit)]
public struct PropVariant
{
[FieldOffset(0)] public short vt;
[FieldOffset(8)] public IntPtr pointerValue;
}
[ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPropertyStore
{
[PreserveSig] int GetCount(out int cProps);
[PreserveSig] int GetAt(int iProp, out PropertyKey pkey);
[PreserveSig] int GetValue(ref PropertyKey key, out PropVariant pv);
[PreserveSig] int SetValue(ref PropertyKey key, ref PropVariant pv);
[PreserveSig] int Commit();
}
[ComImport, Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionManager2
{
[PreserveSig] int GetAudioSessionControl(IntPtr sessionGuid, int streamFlags, out IntPtr sessionControl);
[PreserveSig] int GetSimpleAudioVolume(IntPtr sessionGuid, int streamFlags, out IntPtr audioVolume);
[PreserveSig] int GetSessionEnumerator(out IAudioSessionEnumerator sessionEnum);
[PreserveSig] int RegisterSessionNotification(IntPtr newNotifications);
[PreserveSig] int UnregisterSessionNotification(IntPtr newNotifications);
[PreserveSig] int RegisterDuckNotification(IntPtr sessionId, IntPtr duckNotification);
[PreserveSig] int UnregisterDuckNotification(IntPtr duckNotification);
}
[ComImport, Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionEnumerator
{
[PreserveSig] int GetCount(out int sessionCount);
[PreserveSig] int GetSession(int sessionIndex, out IAudioSessionControl2 session);
}
[ComImport, Guid("bfb7ff88-7239-4fc9-8fa2-07c950be9c6d"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioSessionControl2
{
// IAudioSessionControl
[PreserveSig] int GetState(out int pRetVal);
[PreserveSig] int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig] int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)] string value, IntPtr eventContext);
[PreserveSig] int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig] int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string value, IntPtr eventContext);
[PreserveSig] int GetGroupingParam(out Guid pRetVal);
[PreserveSig] int SetGroupingParam(ref Guid grouping, IntPtr eventContext);
[PreserveSig] int RegisterAudioSessionNotification(IntPtr newNotifications);
[PreserveSig] int UnregisterAudioSessionNotification(IntPtr newNotifications);
// IAudioSessionControl2
[PreserveSig] int GetSessionIdentifier([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig] int GetSessionInstanceIdentifier([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig] int GetProcessId(out int pRetVal);
[PreserveSig] int IsSystemSoundsSession();
[PreserveSig] int SetDuckingPreference(bool optOut);
}
[ComImport, Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAudioMeterInformation
{
[PreserveSig] int GetPeakValue(out float pfPeak);
[PreserveSig] int GetMeteringChannelCount(out int pnChannelCount);
[PreserveSig] int GetChannelsPeakValues(int channelCount, [Out] float[] peakValues);
[PreserveSig] int QueryHardwareSupport(out int pdwHardwareSupportMask);
}
// PowerShell から扱う「普通の .NET オブジェクト」
public class SessionInfo
{
public string Key;
public string Label;
public string Device;
public string ExePath;
public int ProcessId;
private IAudioMeterInformation meter;
public SessionInfo(string key, string label, string device, string exePath, int pid,
IAudioMeterInformation m)
{
Key = key; Label = label; Device = device; ExePath = exePath; ProcessId = pid; meter = m;
}
public float GetPeak()
{
float p = 0f;
try { if (meter.GetPeakValue(out p) != 0) { return 0f; } }
catch { return 0f; }
return p;
}
}
public static class Monitor
{
[DllImport("ole32.dll")]
private static extern int CoCreateInstance(ref Guid rclsid, IntPtr pUnkOuter, int dwClsContext,
ref Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppv);
private static IMMDeviceEnumerator CreateEnumerator()
{
Guid clsid = new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E");
Guid iid = new Guid("A95664D2-9614-4F35-A746-DE8DB63617E6");
object obj;
int hr = CoCreateInstance(ref clsid, IntPtr.Zero, 23 /* CLSCTX_ALL */, ref iid, out obj);
if (hr != 0) { Marshal.ThrowExceptionForHR(hr); }
return (IMMDeviceEnumerator)obj;
}
private static string GetDeviceName(IMMDevice dev)
{
try
{
IPropertyStore store;
if (dev.OpenPropertyStore(0, out store) != 0) { return "(不明なデバイス)"; }
PropertyKey key = new PropertyKey();
key.fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"); // PKEY_Device_FriendlyName
key.pid = 14;
PropVariant pv;
if (store.GetValue(ref key, out pv) != 0) { return "(不明なデバイス)"; }
string s = Marshal.PtrToStringUni(pv.pointerValue);
return string.IsNullOrEmpty(s) ? "(不明なデバイス)" : s;
}
catch { return "(不明なデバイス)"; }
}
public static SessionInfo[] GetSessions()
{
List<SessionInfo> list = new List<SessionInfo>();
IMMDeviceEnumerator devEnum = CreateEnumerator();
IMMDeviceCollection coll;
// dataFlow 0 = eRender(再生) / stateMask 1 = DEVICE_STATE_ACTIVE
if (devEnum.EnumAudioEndpoints(0, 1, out coll) != 0) { return list.ToArray(); }
int devCount;
coll.GetCount(out devCount);
for (int d = 0; d < devCount; d++)
{
IMMDevice dev;
if (coll.Item(d, out dev) != 0) { continue; }
string devName = GetDeviceName(dev);
Guid iid = new Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F");
object mgrObj;
if (dev.Activate(ref iid, 23, IntPtr.Zero, out mgrObj) != 0) { continue; }
IAudioSessionManager2 mgr;
try { mgr = (IAudioSessionManager2)mgrObj; } catch { continue; }
IAudioSessionEnumerator sessEnum;
if (mgr.GetSessionEnumerator(out sessEnum) != 0) { continue; }
int sessCount;
sessEnum.GetCount(out sessCount);
for (int i = 0; i < sessCount; i++)
{
IAudioSessionControl2 sc;
if (sessEnum.GetSession(i, out sc) != 0) { continue; }
IAudioMeterInformation meter;
try { meter = (IAudioMeterInformation)sc; } catch { continue; }
string key = null;
try { sc.GetSessionInstanceIdentifier(out key); } catch { }
if (string.IsNullOrEmpty(key)) { key = devName + "#" + i; }
int pid = 0;
string exePath = "";
string label = Describe(sc, out pid, out exePath);
list.Add(new SessionInfo(key, label, devName, exePath, pid, meter));
}
}
return list.ToArray();
}
private static string Describe(IAudioSessionControl2 sc, out int pid, out string exePath)
{
pid = 0;
exePath = "";
try
{
if (sc.IsSystemSoundsSession() == 0)
{
return "システム音 (Windows の通知音・USB接続音・警告音など)";
}
}
catch { }
try { sc.GetProcessId(out pid); } catch { }
string name = null;
if (pid > 0)
{
try
{
Process p = Process.GetProcessById(pid);
name = p.ProcessName;
try { exePath = p.MainModule.FileName; } catch { }
try
{
if (!string.IsNullOrEmpty(p.MainWindowTitle))
{
name = name + " [" + p.MainWindowTitle + "]";
}
}
catch { }
}
catch { name = "(終了済みプロセス)"; }
}
if (string.IsNullOrEmpty(name))
{
string dn = null;
try { sc.GetDisplayName(out dn); } catch { }
name = string.IsNullOrEmpty(dn) ? "(不明)" : dn;
}
return name + " (PID " + pid + ")";
}
}
}
'@
if (-not ('AudioSpy.Monitor' -as [type])) {
Add-Type -TypeDefinition $csharp -ErrorAction Stop
}
# ===============================================================
# PowerShell 側: 監視ループ
# ===============================================================
function Write-Log {
param([string]$Text, [string]$Color = 'Gray')
Write-Host $Text -ForegroundColor $Color
Add-Content -Path $LogPath -Value $Text -Encoding UTF8
}
$state = @{} # Key -> 鳴っている最中の情報
$summary = @{} # Label -> 回数
$sessions = @()
$lastRefresh = [DateTime]::MinValue
Write-Log ("=" * 72) 'DarkGray'
Write-Log ("音源モニター開始: " + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) 'Cyan'
Write-Log ("ログファイル : $LogPath") 'DarkGray'
Write-Log ("判定しきい値 : $Threshold / 監視間隔: ${PollMs}ms") 'DarkGray'
Write-Log "音が鳴るまで放置してください。停止は Ctrl + C です。" 'Cyan'
Write-Log ("=" * 72) 'DarkGray'
# 起動確認: 現在のセッション一覧を一度表示する
try {
$sessions = [AudioSpy.Monitor]::GetSessions()
$lastRefresh = Get-Date
Write-Log ("現在検出中のオーディオセッション: {0} 件" -f $sessions.Count) 'DarkCyan'
foreach ($s in $sessions) {
Write-Log (" - {0} @ {1}" -f $s.Label, $s.Device) 'DarkGray'
}
Write-Log ("=" * 72) 'DarkGray'
}
catch {
Write-Log ("[エラー] セッション取得に失敗しました: " + $_.Exception.Message) 'Red'
Write-Log ($_.Exception.ToString()) 'DarkRed'
return
}
try {
while ($true) {
$now = Get-Date
if (($now - $lastRefresh).TotalSeconds -ge $RefreshSec) {
try { $sessions = [AudioSpy.Monitor]::GetSessions() }
catch { Write-Log ("[警告] セッション更新に失敗: " + $_.Exception.Message) 'Yellow' }
$lastRefresh = $now
}
foreach ($s in $sessions) {
$peak = $s.GetPeak()
$st = $state[$s.Key]
if ($peak -gt $Threshold) {
if (-not $st) {
$state[$s.Key] = [PSCustomObject]@{
Start = $now
Last = $now
MaxPeak = $peak
Label = $s.Label
}
Write-Log ("{0} ▶ 音の発生 {1}" -f $now.ToString('yyyy-MM-dd HH:mm:ss.fff'), $s.Label) 'Green'
Write-Log ("{0}出力先: {1}" -f (' ' * 27), $s.Device) 'DarkGray'
if ($s.ExePath) {
Write-Log ("{0}実行ファイル: {1}" -f (' ' * 27), $s.ExePath) 'DarkGray'
}
} else {
$st.Last = $now
if ($peak -gt $st.MaxPeak) { $st.MaxPeak = $peak }
}
}
elseif ($st -and ($now - $st.Last).TotalSeconds -ge $SilenceSec) {
$dur = [math]::Round(($st.Last - $st.Start).TotalSeconds, 2)
Write-Log ("{0} ■ 停止 {1} 継続 {2} 秒 / 最大レベル {3}" -f `
$now.ToString('yyyy-MM-dd HH:mm:ss.fff'), $st.Label, $dur,
[math]::Round($st.MaxPeak, 3)) 'DarkGreen'
Write-Log '' 'Gray'
if ($summary.ContainsKey($st.Label)) { $summary[$st.Label]++ } else { $summary[$st.Label] = 1 }
$state.Remove($s.Key)
}
}
Start-Sleep -Milliseconds $PollMs
}
}
finally {
Write-Log ("=" * 72) 'DarkGray'
Write-Log ("監視終了: " + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) 'Cyan'
if ($summary.Count -gt 0) {
Write-Log "" 'Gray'
Write-Log "--- 発生回数の集計 ---" 'Cyan'
$summary.GetEnumerator() | Sort-Object Value -Descending | ForEach-Object {
Write-Log (" {0,4} 回 {1}" -f $_.Value, $_.Key) 'White'
}
} else {
Write-Log "この間に音は検出されませんでした。" 'Yellow'
}
Write-Log ("ログ: $LogPath") 'DarkGray'
Write-Log ("=" * 72) 'DarkGray'
}
<#
================================================================
watch-wsl-launcher.ps1
wsl.exe / bash.exe の起動を監視し、「誰が起動したか」を
親プロセスをさかのぼって記録するスクリプト
使い方:
powershell -ExecutionPolicy Bypass -File "<このファイルのパス>"
停止は Ctrl + C
仕組み:
Win32_Process を 0.4 秒ごとにポーリングし、新しく現れた
wsl.exe / bash.exe / wslhost.exe のコマンドラインと、
その親プロセスの系譜を PID までさかのぼって記録する。
管理者権限は不要。
================================================================
#>
param(
[int] $PollMs = 400,
[string]$LogPath = "",
# 監視対象のプロセス名(必要なら増やす)
[string[]]$TargetNames = @('wsl.exe', 'bash.exe', 'wslhost.exe', 'ubuntu.exe', 'wt.exe')
)
if ([string]::IsNullOrWhiteSpace($LogPath)) {
$baseDir = if ($PSScriptRoot) { $PSScriptRoot } else { [Environment]::GetFolderPath('Desktop') }
$LogPath = Join-Path $baseDir 'wsl-launcher-log.txt'
}
function Write-Log {
param([string]$Text, [string]$Color = 'Gray')
Write-Host $Text -ForegroundColor $Color
Add-Content -Path $LogPath -Value $Text -Encoding UTF8
}
# WQL のフィルタ文字列を組み立てる
$filter = ($TargetNames | ForEach-Object { "Name='$_'" }) -join ' OR '
function Get-ProcById {
param([int]$Id)
if ($Id -le 0) { return $null }
try { return Get-CimInstance Win32_Process -Filter "ProcessId=$Id" -ErrorAction Stop } catch { return $null }
}
function Write-Ancestry {
param([int]$StartPid)
$current = $StartPid
$depth = 1
while ($depth -le 12) {
$p = Get-ProcById $current
if (-not $p) { break }
$parentId = [int]$p.ParentProcessId
if ($parentId -le 0) { break }
$parent = Get-ProcById $parentId
if (-not $parent) {
Write-Log (" [{0}] PID {1} (すでに終了しているため詳細不明)" -f $depth, $parentId) 'DarkYellow'
break
}
Write-Log (" [{0}] PID {1} {2}" -f $depth, $parent.ProcessId, $parent.Name) 'White'
if ($parent.ExecutablePath) {
Write-Log (" パス : {0}" -f $parent.ExecutablePath) 'DarkGray'
}
if ($parent.CommandLine) {
Write-Log (" コマンド: {0}" -f $parent.CommandLine) 'DarkGray'
}
if ($parent.CreationDate) {
Write-Log (" 起動 : {0}" -f $parent.CreationDate) 'DarkGray'
}
# System / Idle まで来たら終了
if ($parent.ProcessId -le 4) { break }
$current = $parentId
$depth++
}
}
$seen = @{}
$hitCount = 0
$lastHit = $null
Write-Log ("=" * 72) 'DarkGray'
Write-Log ("WSL 起動元モニター開始: " + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) 'Cyan'
Write-Log ("ログファイル: $LogPath") 'DarkGray'
Write-Log ("監視対象 : " + ($TargetNames -join ', ')) 'DarkGray'
Write-Log "対象プロセスが起動するまで放置してください。停止は Ctrl + C です。" 'Cyan'
Write-Log ("=" * 72) 'DarkGray'
# 起動時点で存在するものは既知として無視する(今動いているセッションを拾わないため)
try {
Get-CimInstance Win32_Process -Filter $filter -ErrorAction Stop | ForEach-Object {
$seen[[int]$_.ProcessId] = $true
}
Write-Log ("既存プロセス {0} 件を除外しました。ここから新規起動のみ記録します。" -f $seen.Count) 'DarkCyan'
Write-Log ("=" * 72) 'DarkGray'
}
catch {
Write-Log ("[エラー] プロセス一覧の取得に失敗: " + $_.Exception.Message) 'Red'
return
}
try {
while ($true) {
$now = Get-Date
try { $procs = @(Get-CimInstance Win32_Process -Filter $filter -ErrorAction Stop) }
catch { $procs = @() }
$alive = @{}
foreach ($p in $procs) {
$procId = [int]$p.ProcessId
$alive[$procId] = $true
if ($seen.ContainsKey($procId)) { continue }
$seen[$procId] = $true
$hitCount++
$interval = ''
if ($lastHit) {
$span = $now - $lastHit
$interval = (" 前回から {0:n1} 秒 ({1:n2} 分)" -f $span.TotalSeconds, $span.TotalMinutes)
}
$lastHit = $now
Write-Log ("{0} ▶ 起動検出 #{1} {2} (PID {3}){4}" -f `
$now.ToString('yyyy-MM-dd HH:mm:ss.fff'), $hitCount, $p.Name, $procId, $interval) 'Green'
if ($p.CommandLine) {
Write-Log (" コマンド: {0}" -f $p.CommandLine) 'Yellow'
}
Write-Log " --- 親プロセスの系譜 ---" 'DarkCyan'
Write-Ancestry -StartPid $procId
Write-Log '' 'Gray'
}
# 終了したプロセスを掃除
foreach ($k in @($seen.Keys)) {
if (-not $alive.ContainsKey($k)) { $seen.Remove($k) }
}
Start-Sleep -Milliseconds $PollMs
}
}
finally {
Write-Log ("=" * 72) 'DarkGray'
Write-Log ("監視終了: " + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + " 検出 $hitCount 件") 'Cyan'
Write-Log ("ログ: $LogPath") 'DarkGray'
Write-Log ("=" * 72) 'DarkGray'
}
#!/usr/bin/env bash
# ================================================================
# wsl-audio-source-logger.sh
# WSL (WSLg) の中で、どの Linux プロセスが音を鳴らしたかを記録する
#
# 使い方:
# wsl # WSL に入る
# bash /path/to/wsl-audio-source-logger.sh
#
# 停止は Ctrl + C
#
# 仕組み:
# WSLg は PulseAudio 経由で音声を Windows に転送している。
# 再生ストリーム (sink-input) の出現・再開を 0.2 秒ごとに監視し、
# アプリ名・実行ファイル・PID・コマンドラインを記録する。
# ================================================================
set -u
LOG="${1:-$HOME/wsl-audio-source-log.txt}"
log() {
echo "$1"
echo "$1" >> "$LOG"
}
# --- 事前チェック ------------------------------------------------
if ! command -v pactl >/dev/null 2>&1; then
echo "pactl が見つかりません。次のコマンドでインストールしてください:"
echo " sudo apt update && sudo apt install -y pulseaudio-utils"
exit 1
fi
if ! pactl info >/dev/null 2>&1; then
echo "PulseAudio サーバーに接続できません。"
echo "PULSE_SERVER の値: ${PULSE_SERVER:-(未設定)}"
echo "WSLg が有効な環境で実行しているか確認してください"
echo "(/mnt/wslg/PulseServer が存在するはずです)。"
exit 1
fi
log "========================================================================"
log "WSL 音源モニター開始: $(date '+%Y-%m-%d %H:%M:%S')"
log "ログファイル: $LOG"
log "PulseAudio : $(pactl info | grep -i 'Server Name' | head -1)"
log "音が鳴るまで放置してください。停止は Ctrl + C です。"
log "========================================================================"
# --- ストリームの詳細を取得 --------------------------------------
describe_stream() {
local idx="$1"
pactl list sink-inputs 2>/dev/null | awk -v want="$idx" '
/^Sink Input #/ {
cur = $0
sub(/^Sink Input #/, "", cur)
inblock = (cur + 0 == want + 0)
}
inblock {
if ($0 ~ /application\.name = /) { name = extract($0) }
if ($0 ~ /application\.process\.binary = /) { bin = extract($0) }
if ($0 ~ /application\.process\.id = /) { pid = extract($0) }
if ($0 ~ /media\.name = /) { media= extract($0) }
}
END {
printf "%s|%s|%s|%s", (name?name:"?"), (bin?bin:"?"), (pid?pid:"?"), (media?media:"?")
}
function extract(line, n) {
n = line
sub(/^[^=]*= /, "", n)
gsub(/^"|"$/, "", n)
return n
}
'
}
# --- 親プロセスを PID 1 までさかのぼる ---------------------------
walk_ancestors() {
local p="$1"
local depth=1
local cmd start
while [ -n "$p" ] && [ "$p" != "0" ] && [ "$depth" -le 15 ]; do
p="$(awk '/^PPid:/{print $2}' "/proc/$p/status" 2>/dev/null)"
[ -z "${p:-}" ] && break
[ "$p" = "0" ] && break
cmd="$(tr '\0' ' ' < "/proc/$p/cmdline" 2>/dev/null)"
[ -z "$cmd" ] && cmd="[$(cat "/proc/$p/comm" 2>/dev/null)]"
# プロセスの起動時刻も出す(常駐か毎回起動かの判別に使う)
start="$(ps -o lstart= -p "$p" 2>/dev/null | sed 's/^ *//')"
log " [$depth] PID $p $cmd"
[ -n "${start:-}" ] && log " 起動: $start"
[ "$p" = "1" ] && break
depth=$((depth + 1))
done
}
# --- メインループ ------------------------------------------------
declare -A seen # index -> 1
declare -A corked # index -> yes/no
trap 'log "========================================================================"; log "監視終了: $(date "+%Y-%m-%d %H:%M:%S")"; log "ログ: $LOG"; exit 0' INT TERM
while true; do
# index と corked 状態の一覧
snapshot="$(pactl list sink-inputs 2>/dev/null | awk '
/^Sink Input #/ { idx = $0; sub(/^Sink Input #/, "", idx) }
/^[[:space:]]*Corked:/ { print idx "\t" $2 }
')"
current=""
while IFS=$'\t' read -r idx ck; do
[ -z "${idx:-}" ] && continue
current="$current $idx"
if [ -z "${seen[$idx]:-}" ]; then
# 新しい再生ストリームが出現した
info="$(describe_stream "$idx")"
IFS='|' read -r name bin pid media <<< "$info"
ts="$(date '+%Y-%m-%d %H:%M:%S.%3N')"
log "$ts ▶ 音の発生 ${name} (PID ${pid})"
log " 実行ファイル: ${bin}"
log " ストリーム名: ${media}"
if [ "${pid}" != "?" ] && [ -r "/proc/${pid}/cmdline" ]; then
cmd="$(tr '\0' ' ' < "/proc/${pid}/cmdline")"
log " コマンド : ${cmd}"
log " --- 親プロセスの系譜 (PID 1 まで) ---"
walk_ancestors "$pid"
fi
log ""
seen[$idx]=1
elif [ "${corked[$idx]:-}" = "yes" ] && [ "$ck" = "no" ]; then
# 一時停止していたストリームが再開した
info="$(describe_stream "$idx")"
IFS='|' read -r name bin pid media <<< "$info"
ts="$(date '+%Y-%m-%d %H:%M:%S.%3N')"
log "$ts ▶ 再生再開 ${name} (PID ${pid}) ${media}"
log ""
fi
corked[$idx]="$ck"
done <<< "$snapshot"
# 消えたストリームを掃除
for idx in "${!seen[@]}"; do
case " $current " in
*" $idx "*) ;;
*) unset "seen[$idx]"; unset "corked[$idx]" ;;
esac
done
sleep 0.2
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment