// Global variables
winrt::com_ptr<IAudioStateMonitor> g_audioStateMonitor;
AudioStateMonitorRegistrationHandle g_registration = 0;
// Returns true if the GameMedia stream is to be disabled, false if it's to be enabled.
bool IsSoundLevelMuted(_In_ IAudioStateMonitor* audioStateMonitor)
{
return (audioStateMonitor->GetSoundLevel() == AudioStateMonitorSoundLevel::Muted);
}
HRESULT StartTrackingSoundLevel()
{
// Create an AudioStateMonitor, and register for callbacks from it.
HRESULT hr = RegisterForSoundLevelChanges();
if (SUCCEEDED(hr))
{
// Check the current sound level, and determine whether the GameMedia stream is to be enabled.
bool disableGameMediaStream = IsSoundLevelMuted(g_audioStateMonitor.get());
// Here, add code that enables or disables the GameMedia stream
// according to the value of the Boolean.
}
return hr;
}
HRESULT RegisterForSoundLevelChanges()
{
HRESULT hr = S_OK;
// Create a new AudioStateMonitor for the GameMedia category, if needed, and register for callbacks.
if (m_audioStateMonitor == nullptr)
{
hr = CreateRenderAudioStateMonitorForCategoryAndDeviceRole(
AudioCategory_GameMedia, ERole::eConsole, g_audioStateMonitor.put());
if (SUCCEEDED(hr))
{
// Optional "context" parameter is not used in this example
// and is set to nullptr.
hr = g_audioStateMonitor->RegisterCallback(OnAudioStateMonitorCallback, nullptr, &g_registration);
}
}
if (FAILED(hr))
{
// g_audioStateMonitor is a smart pointer, so if an IAudioStateMonitor
// was allocated, then setting the smart pointer to null invokes the
// Release method, which will decrement its usage count and ensure that
// the object is destroyed properly.
g_audioStateMonitor = nullptr;
}
return hr;
}
// Unregister callbacks on program shutdown
void UnregisterForSoundLevelChanges()
{
if (g_audioStateMonitor != nullptr)
{
if (g_registration)
{
g_audioStateMonitor->UnregisterCallback(g_registration);
}
// g_audioStateMonitor is a smart pointer, so setting it to null
// will invoke the Release method to decrement its usage count.
g_audioStateMonitor = nullptr;
}
}
void OnAudioStateMonitorCallback(_In_ IAudioStateMonitor* audioStateMonitor, _In_opt_ void* context)
{
bool disableGameMediaStream = IsSoundLevelMuted(audioStateMonitor);
// Add code here that enables or disables the GameMedia stream
// according to the value of the Boolean.
}