使用c#检查音频是否在PC上工作
本文关键字:PC 工作 是否 检查 音频 使用 | 更新日期: 2023-09-27 18:14:25
我想播放视频,但在播放视频之前,我想知道连接到系统的音频设备是否正常工作。
public static bool IsAudioDeviceAvailable()
{
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_SoundDevice");
ManagementObjectCollection objCollection = objSearcher.Get();
if(objCollection.Count > 0)
{
return true;
}
else
{
return false;
}
}
但是行不通
我使用user3060520建议的解决方案
检测音频输入&连接到系统的输出设备
public static bool IsAudioDeviceAvailable()
{
string[] mydevices = null;
mydevices = Win32.GetSoundDevices();
if (mydevices.Count() > 0)
{
return true;
}
else
{
return false;
}
}
}
public class Win32
{
[DllImport("winmm.dll", SetLastError = true)]
static extern uint waveOutGetNumDevs();
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint waveOutGetDevCaps(uint hwo, ref WAVEOUTCAPS pwoc, uint cbwoc);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct WAVEOUTCAPS
{
public ushort wMid;
public ushort wPid;
public uint vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string szPname;
public uint dwFormats;
public ushort wChannels;
public ushort wReserved1;
public uint dwSupport;
}
public static string[] GetSoundDevices()
{
uint devices = waveOutGetNumDevs();
string[] result = new string[devices];
WAVEOUTCAPS caps = new WAVEOUTCAPS();
for (uint i = 0; i < devices; i++)
{
waveOutGetDevCaps(i, ref caps, (uint)Marshal.SizeOf(caps));
result[i] = caps.szPname;
}
return result;
}
我还想补充的是,它将不工作的虚拟音频设备。
您还可以使用devcon.exe通过ID/class等查找设备并解析其状态。如:
devcon.exe status =media //this will find all media devices and show its tatus
devcon.exe status [Device HW ID] //this will find device by id and show its status
样本输出:devcon.exe status [Device HW ID]
Device HW ID
Name: Realtek High Definition Audio
Driver is running.
现在你只需要解析输出字符串寻找"驱动程序正在运行"或类似的东西来检测设备驱动程序是否正常工作。你可以在这里找到更多关于devcon的信息