Exemplo n.º 1
0
        private static ISimpleAudioVolume GetVolumeObject(int pid)
        {
            // get the speakers (1st render + multimedia) device
            IMmDeviceEnumerator deviceEnumerator = (IMmDeviceEnumerator)(new MMDeviceEnumerator());
            IMmDevice           speakers;

            deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.ERender, ERole.EMultimedia, out speakers);

            string defaultDeviceId;

            speakers.GetId(out defaultDeviceId);

            ISimpleAudioVolume volumeControl = GetVolumeObject(pid, speakers);

            Marshal.ReleaseComObject(speakers);

            if (volumeControl == null)
            {
                // If volumeControl is null, then the process's volume object might be on a different device.
                // This happens if the process doesn't use the default device.
                //
                // As far as Spotify is concerned, if using the "--enable-audio-graph" command line argument,
                // a new option becomes available in the Settings that makes it possible to change the playback device.

                IMmDeviceCollection deviceCollection;
                deviceEnumerator.EnumAudioEndpoints(EDataFlow.ERender, EDeviceState.Active, out deviceCollection);

                int count;
                deviceCollection.GetCount(out count);
                for (int i = 0; i < count; i++)
                {
                    IMmDevice device;
                    deviceCollection.Item(i, out device);

                    string deviceId;
                    device.GetId(out deviceId);

                    try
                    {
                        if (deviceId == defaultDeviceId)
                        {
                            continue;
                        }

                        volumeControl = GetVolumeObject(pid, device);
                        if (volumeControl != null)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(device);
                    }
                }
            }

            Marshal.ReleaseComObject(deviceEnumerator);
            return(volumeControl);
        }