Exemplo n.º 1
0
    private async Task UpdateStateAsync(
        PcAudio audioUpdate, CoreAudioController coreAudioController, CancellationToken stoppingToken)
    {
        if (audioUpdate?.DefaultDevice == null)
        {
            return;
        }

        var defaultPlaybackDevice = coreAudioController.DefaultPlaybackDevice;

        // Change default audio device.
        if (audioUpdate.DefaultDevice.DeviceId != defaultPlaybackDevice.Id.ToString())
        {
            var deviceId = Guid.Parse(audioUpdate.DefaultDevice.DeviceId);
            var newDefaultAudioDevice = await coreAudioController.GetDeviceAsync(deviceId);

            await newDefaultAudioDevice.SetAsDefaultAsync(stoppingToken);

            await newDefaultAudioDevice.SetAsDefaultCommunicationsAsync(stoppingToken);

            return;
        }

        // Change muted and / or volume values.
        if (audioUpdate.DefaultDevice.MasterMuted.HasValue)
        {
            var muted = audioUpdate.DefaultDevice.MasterMuted.Value;

            if (muted != defaultPlaybackDevice.IsMuted)
            {
                await defaultPlaybackDevice.SetMuteAsync(muted, stoppingToken);
            }
        }
        if (audioUpdate.DefaultDevice.MasterVolume.HasValue)
        {
            const int increment = 2;

            var deviceAudioVolume = defaultPlaybackDevice.Volume;
            var clientAudioVolume = audioUpdate.DefaultDevice.MasterVolume.Value;

            var volume = deviceAudioVolume;
            if (clientAudioVolume < deviceAudioVolume)
            {
                volume -= increment;
            }
            else if (clientAudioVolume > deviceAudioVolume)
            {
                volume += increment;
            }

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (volume != deviceAudioVolume)
            {
                await defaultPlaybackDevice.SetVolumeAsync(volume, stoppingToken);
            }
        }
    }