How to check if a process plays sound?

215 Views Asked by At

My current Code is:

public static MMDevice GetDefaultRenderDevice()
    {
        using (var enumerator = new MMDeviceEnumerator())
        {
            return enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
        }
    }

    public static bool IsAudioPlaying(MMDevice device)
    {
        using (var meter = AudioMeterInformation.FromDevice(device))
        {
            return meter.PeakValue > 0;
        }
    }

When I say Console.WriteLine(IsAudioPlaying(GetDefaultRenderDevice())); it only tells if any sound is played. What can I do if I only want it to check if for example chrome plays a sound?

1

There are 1 best solutions below

0
Florian On

You can use the AudioSession api. Take a look at the AudioSessionTests of cscore. https://github.com/filoe/cscore/blob/master/CSCore.Test/CoreAudioAPI/AudioSessionTests.cs

It might work using something like this:

using (var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
{
    using (var sessionEnumerator = sessionManager.GetSessionEnumerator())
    {
        foreach (var session in sessionEnumerator)
        {
            //one of the sessions is might be google chrome
            //implement your logic to select the correct session

            using (var meterInformation = session.QueryInterface<AudioMeterInformation>())
            {
                var peak = meterInformation.PeakValue;
                //implement your logic
            }
        }
    }
}

... 

private AudioSessionManager2 GetDefaultAudioSessionManager2(DataFlow dataFlow)
{
    using (var enumerator = new MMDeviceEnumerator())
    {
        using (var device = enumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia))
        {
            Debug.WriteLine("DefaultDevice: " + device.FriendlyName);
            var sessionManager = AudioSessionManager2.FromMMDevice(device);
            return sessionManager;
        }
    }
}