使用C#检查音频是否在PC上运行?

时间:2016-10-21 10:50:04

标签: c# audio

我想播放视频,但在播放视频之前,我想知道连接到系统的音频设备是否正常工作。

  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建议的解决方案

Detecting Audio Input & output devices connected to system

  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;
    }

此外,我想补充一点,它不适用于虚拟音频设备。

1 个答案:

答案 0 :(得分:0)

您还可以使用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.

现在你只需要解析输出字符串,寻找&#34;驱动程序正在运行&#34;或类似的确实检测到设备驱动程序正常工作。 你可以找到更多关于devcon here

的信息