|
<# |
|
================================================================ |
|
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' |
|
} |