c - 掌握Windows 10的声音管理

标签 c winapi audio

我需要在 Windows 10 中更改主音量,但我只能更改我的应用程序的音量。有人知道如何在 C 中做到这一点吗?

也许使用 Windows API?

最佳答案

自 Windows Vista 以来,我们有:

  1. 流量
  2. 简单卷
  3. channel 流量
  4. 端点量

您需要更改 endpoint volume .所以你需要 IAudioEndpointVolume界面。

下面代码中的步骤是获取一个IMMDeviceEnumerator。使用枚举器,您可以使用 GetDefaultAudioEndpoint 获取默认音频端点。在IAudioEndpointVolume界面中找到Get/SetMasterVolumeLevel

以下示例代码摘自Larry Osterman's blog .请注意,没有错误检查。

#include <stdio.h>
#include <windows.h>
#include <tchar.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>

void Usage()
{
  printf("Usage: \n");
  printf(" SetVolume [Reports the current volume]\n");
  printf(" SetVolume -d <new volume in decibels> [Sets the current default render device volume to the new volume]\n");
  printf(" SetVolume -f <new volume as an amplitude scalar> [Sets the current default render device volume to the new volume]\n");

}
int _tmain(int argc, _TCHAR* argv[])
{
  HRESULT hr;
  bool decibels = false;
  bool scalar = false;
  double newVolume;
  if (argc != 3 && argc != 1)
  {
    Usage();
    return -1;
  }
  if (argc == 3)
  {
    if (argv[1][0] == '-')
    {
      if (argv[1][1] == 'f')
      { 
        scalar = true;
      }
      else if (argv[1][1] == 'd')
      {
        decibels = true;
      }
    }
    else
    {
      Usage();
      return -1;
    }

    newVolume = _tstof(argv[2]);
  }

  // -------------------------
  CoInitialize(NULL);
  IMMDeviceEnumerator *deviceEnumerator = NULL;
  hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID *)&deviceEnumerator);
  IMMDevice *defaultDevice = NULL;

  hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
  deviceEnumerator->Release();
  deviceEnumerator = NULL;

  IAudioEndpointVolume *endpointVolume = NULL;
  hr = defaultDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, (LPVOID *)&endpointVolume);
  defaultDevice->Release();
  defaultDevice = NULL; 

  // -------------------------
  float currentVolume = 0;
  endpointVolume->GetMasterVolumeLevel(&currentVolume);
  printf("Current volume in dB is: %f\n", currentVolume);

  hr = endpointVolume->GetMasterVolumeLevelScalar(&currentVolume);
  printf("Current volume as a scalar is: %f\n", currentVolume);
  if (decibels)
  {
    hr = endpointVolume->SetMasterVolumeLevel((float)newVolume, NULL);
  }
  else if (scalar)
  {
    hr = endpointVolume->SetMasterVolumeLevelScalar((float)newVolume, NULL);
  }
  endpointVolume->Release();

  CoUninitialize();
  return 0;
}

关于c - 掌握Windows 10的声音管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46905861/

相关文章:

iOS smbPitchShift 不起作用

android - 根据关联的音频文件拦截 Android 通知?

ios - ios 7-用于录制和播放的AVAudioRecorder或AudioToolbox-不作为文件-作为缓冲区

c - C语言中的Unix命令 "ls"

c - 当用户输入数字时如何打印文件中的特定行

c# - 使用 System.Diagnostics.Process() 为进程设置图像名称和描述

c++ - CryptEncrypt 的合适替代方案

c++ - c 中 %f 说明符的不可预测行为

c++ - 仅在打开编译器优化的情况下,某些地方的缓冲区溢出

C win32包装器