Get and set audio device volume under Windows system

Source: Internet
Author: User

first, get the device volume

Different systems to get the volume of the method is different, such as Vista and Win7 to get the volume of the way is not the same, so we should first obtain the system information, and then according to the system information, the corresponding method to obtain the volume.

1, osVersionInfoSystem Information Structure body

The following structures are used to retrieve or set system information.


Instructions for use
Contains the operating system version information in the OSVERSIONINFO data structure. This information includes major and minor version numbers, a build number, a platform identifier, and descriptive text for the operating system. The GetVersionEx function will use this struct.

Structure prototype:

typedef struct _osversioninfo{    DWORD dwosversioninfosize;    DWORD dwMajorVersion;    DWORD dwMinorVersion;    DWORD dwBuildNumber;    DWORD dwPlatformId;    TCHAR szcsdversion[128];} osVersionInfo;
 

member Description:
1) dwOSVersionInfoSize
Specifies the size of this data structure, in bytes. This member must be set to sizeof (OSVERSIONINFO) before calling the GetVersionEx (OSVERSIONINFO) function.
2) dwMajorVersion
identifies the major version number of the operating system. For example, for Windows NT version 3.51, the major version number is 3, and for Windows NT version 4.0, the major version number is 4.
3) dwMinorVersion
identifies the minor version number of the operating system. For example, for Windows NT version 3.51, the minor version number is 51, and for Windows NT 4.0, the minor version number is 0.
4) dwBuildNumber
Windows NT: Identifies the build number of the operating system.
Windows 95: Low word identifies the build number of the operating system number. The high word contains the major and minor version numbers.
5) dwPlatformId
identifies the operating system platform. This member can be one of the following values:
6) szCSDVersion
Windows NT: Contains a null-terminated string, such as Service Pack 3, that indicates that the latest service pack is installed on the system. If the service Pack is not installed, the string is empty.
Windows 95: Contains a null-terminated string that provides any supplemental information to the operating system.


Application:

osVersionInfo osver;osver.dwosversioninfosize = sizeof (OSVERSIONINFO);:: GetVersionEx (&osver); if ( osver.dwmajorversion==6) {        getaudioouputvolum_vita ();    }    else    {        getaudioouputvolum_win7 ();    }

2. Get device volume under Vista

int Getaudiooutputvolumn_vista (const std::string &devicename) {immdeviceenumerator* penumerator;    immdevicecollection* pcollection = NULL;    Immdevice *pdevice = NULL;      IPropertyStore *pproperties=null;      Iaudioendpointvolume *pvolumeapi=null;    UINT devicecount = 0;    float Fvolume =-1;    CoInitializeEx (NULL, coinit_multithreaded); HRESULT hr=cocreateinstance (__uuidof (mmdeviceenumerator), Null,clsctx_all, __uuidof (Immdeviceenumerator), (void**)    &penumerator);          if (hr! = S_OK) {printf ("CoCreateInstance failed!\n");      return 0;    }//hr = Penumerator->enumaudioendpoints (ecapture/*erender*/, device_state_active, &pCollection);    hr = Penumerator->enumaudioendpoints (Erender, device_state_active, &pcollection);          if (hr! = S_OK) {printf ("enumaudioendpoints failed!\n");      Goto Releasepenumerator;      } hr = Pcollection->getcount (&devicecount);     if (hr! = S_OK) {     printf ("GetCount failed!\n");      Goto releasepcollection;          } for (UINT dev=0;dev<devicecount;dev++) {pdevice = NULL;          hr = Pcollection->item (dev,&pdevice);              if (hr = S_OK) {hr = Pdevice->openpropertystore (stgm_read,&pproperties);                  if (hr = S_OK) {propvariant varName;                  Propvariantinit (&varname);                 hr = Pproperties->getvalue (Pkey_device_friendlyname, &varname);                         if (SUCCEEDED (HR)) {if (varname.vt! = Vt_lpwstr | | (Wstr2str (Varname.pwszval). FIND (devicename)! = 0))                    The value passed in may be incomplete and requires the first part to match {continue;                      } hr=pdevice->activate (__uuidof (Iaudioendpointvolume), Clsctx_all,null, (void * *) (&AMP;PVOLUMEAPI));           if (HR==S_OK) {               hr = Pvolumeapi->getmastervolumelevelscalar (&fvolume);                    if (S_OK = = hr) break;              }} safe_release (Pproperties);          } safe_release (pdevice);  }} releasepcollection:safe_release (Pcollection);      Releasepenumerator:safe_release (Penumerator); return fvolume*100;}

3, Win7 to get the device volume

There are several APIs under Windows:

The Mixeropen and Mixerclose functions are used to turn the mixer device on and off

Mixergetnumdevs can determine how many mixer devices are in the system

The Mixergetdevcaps function can determine the capabilities of the mixer device

Mixergetlineinfo can retrieve information for a specified audio line

Mixergetlinecontrols Common information used to retrieve one or more controls associated with an audio line

Mixergetcontroldetails used to retrieve the properties of a control associated with an audio line

The mixersetcontroldetails is used to set the properties of the development control.


int getaudiooutputvolumn_win7 (const std::string &devicename) {Mmresult rc; The multimedia function returns the result variable hmixer hmixer;    Mixer device handle Mixerline MXL;   Audio Line standard state information structure body Mixerlinecontrols mxlc;    Audio Line Controller set information structure body Mixercontrol MXC;  Single Audio line controller information structure//open mixer Device rc = Mixeropen (&hmixer,//return device handle 0,//single sound card with device ID 0,//      Do not use callback mechanism 0,//callback function parameter 0);        The value of the Mixer_objectf_mixer macro, which indicates that the optional valid device ID//Open mixer device is error-free, then if (mmsyserr_noerror = = RC) {//mixerline struct variable zeroing        ZeroMemory (&AMP;MXL, sizeof (Mixerline)); mxl.cbstruct = sizeof (mixerline); Microsoft use this method to determine the version//point out the need to obtain the channel, sound card audio output with mixerline_componenttype_dst_speakers Mxl.dwcomponenttype = Mixerline_comp        Onenttype_dst_speakers; Obtain the specified line information for the mixer device rc = Mixergetlineinfo ((hmixerobj) hmixer, &AMP;MXL,//Get Mixerline::d wcompon   Enttype The first audio line information for a specified type Mixer_getlineinfof_componenttype);     If the specified line information of the mixer device is obtained successfully, then if (mmsyserr_noerror = = RC) {//mixercontrol struct variable 0 Zer            Omemory (&AMP;MXC, sizeof (Mixercontrol)); mxc.cbstruct = sizeof (MXC);            Microsoft uses this method to judge version//mixerlinecontrols structure variable clear 0 zeromemory (&mxlc, sizeof (Mixerlinecontrols)); mxlc.cbstruct = sizeof (MXLC); Microsoft uses this method to judge version Mxlc.dwlineid = Mxl.dwlineid;            The sound card audio output line ID obtained above//control type is control volume Mxlc.dwcontroltype = mixercontrol_controltype_volume;          Mxlc.ccontrols = 1;        Use mixercontrol struct variable number Mxlc.pamxctrl = &mxc; Mixercontrol struct variable pointer mxlc.cbmxctrl = sizeof (MXC); Mixercontrol structure variable byte size//Get controller information rc = Mixergetlinecontrols ((hmixerobj) hmixer, &am            P;MXLC, Mixer_getlinecontrolsf_onebytype); If the controller information is obtained successfully, then if (mmsyserr_noerror = = RC) {//Gets the volume range of the value in the controller: MXC. Bounds.lMinimum to Mxc.Bounds.lMaximum mixercontroldetails Mxcd; The state information of the controller mixercontroldetails_signed volstruct;                Volume structure variable (for one Member)//mixercontroldetails structure variable clear 0 zeromemory (&mxcd, sizeof (MXCD));       mxcd.cbstruct = sizeof (MXCD); Microsoft uses this method to judge version mxcd.dwcontrolid = Mxc.dwcontrolid;        The controller ID obtained above mxcd.padetails = &volStruct; Volume structure body variable pointer mxcd.cbdetails = sizeof (volstruct);                 Volume structure body variable byte size mxcd.cchannels = 1; Get or set all channels//Gets the volume range of the values in the controller: MXC. Bounds.lminimum to Mxc.Bounds.lMaximum.//Get volume value rc = Mixergetcontroldetails ((hmixerobj) hmixer                , &mxcd, Mixer_getcontroldetailsf_value); if (mmsyserr_noerror = = RC) {Long step = (MXC. Bounds.lmaximum-mxc.                    bounds.lminimum)/100; Int index = (VOLSTRUCT.LVALUE-MXC.                    Bounds.lminimum)/step;                    printf ("Volume:%x", volstruct.lvalue);                return index; }            }        }    }}

second, set the device volume

Set volume and get volume most of the code is the same, just a few words.

1. Set device volume under Vista

int Setaudiooutputvolum_vista (int volumnindex) {immdeviceenumerator* penumerator;    immdevicecollection* pcollection = NULL;    Immdevice *pdevice = NULL;      IPropertyStore *pproperties=null;      Iaudioendpointvolume *pvolumeapi=null;    UINT devicecount = 0;    float Fvolume =-1;    CoInitializeEx (NULL, coinit_multithreaded); HRESULT hr=cocreateinstance (__uuidof (mmdeviceenumerator), Null,clsctx_all, __uuidof (Immdeviceenumerator), (void**)    &penumerator);          if (hr! = S_OK) {printf ("CoCreateInstance failed!\n");      return 0;    }//hr = Penumerator->enumaudioendpoints (ecapture/*erender*/, device_state_active, &pCollection);    hr = Penumerator->enumaudioendpoints (Erender, device_state_active, &pcollection);          if (hr! = S_OK) {printf ("enumaudioendpoints failed!\n");      Goto Releasepenumerator;      } hr = Pcollection->getcount (&devicecount); if (hr! = S_OK) {printf ("GetcouNT Failed!\n ");      Goto releasepcollection;          } for (UINT dev=0;dev<devicecount;dev++) {pdevice = NULL;          hr = Pcollection->item (dev,&pdevice);              if (hr = S_OK) {hr = Pdevice->openpropertystore (stgm_read,&pproperties);                  if (hr = S_OK) {propvariant varName;                  Propvariantinit (&varname);                 hr = Pproperties->getvalue (Pkey_device_friendlyname, &varname); if (SUCCEEDED (HR)) {hr=pdevice->activate (__uuidof (Iaudioendpointvolume), Clsctx_all,                      NULL, (void * *) (&AMP;PVOLUMEAPI));                        if (HR==S_OK) {float volumnlevel = (float) volumnindex/100; hr = <span style= "color: #ff6666;" >pvolumeapi->setmastervolumelevelscalar (Volumnlevel, NULL);</span>}}               Safe_release (pproperties);          } safe_release (pdevice);  }} releasepcollection:safe_release (Pcollection);      Releasepenumerator:safe_release (Penumerator); return fvolume*100;}


2. Set the device volume under Win7

int setaudiooutputvolum_win7 (int volumnindex) {Mmresult rc; The multimedia function returns the result variable hmixer hmixer;    Mixer device handle Mixerline MXL;   Audio Line standard state information structure body Mixerlinecontrols mxlc;    Audio Line Controller set information structure body Mixercontrol MXC;  Single Audio line controller information structure//open mixer Device rc = Mixeropen (&hmixer,//return device handle 0,//single sound card with device ID 0,//      Do not use callback mechanism 0,//callback function parameter 0);        The value of the Mixer_objectf_mixer macro, which indicates that the optional valid device ID//Open mixer device is error-free, then if (mmsyserr_noerror = = RC) {//mixerline struct variable zeroing        ZeroMemory (&AMP;MXL, sizeof (Mixerline)); mxl.cbstruct = sizeof (mixerline); Microsoft use this method to determine the version//point out the need to obtain the channel, sound card audio output with mixerline_componenttype_dst_speakers Mxl.dwcomponenttype = Mixerline_comp        Onenttype_dst_speakers; Obtain the specified line information for the mixer device rc = Mixergetlineinfo ((hmixerobj) hmixer, &AMP;MXL,//Get Mixerline::d wcompon        Enttype The first audio line information for a specified type Mixer_getlineinfof_componenttype); Get the specified line for the mixer deviceIf the path information succeeds, then if (mmsyserr_noerror = = RC) {//mixercontrol struct variable 0 zeromemory (&AMP;MXC, S            Izeof (Mixercontrol)); mxc.cbstruct = sizeof (MXC);            Microsoft uses this method to judge version//mixerlinecontrols structure variable clear 0 zeromemory (&mxlc, sizeof (Mixerlinecontrols)); mxlc.cbstruct = sizeof (MXLC); Microsoft uses this method to judge version Mxlc.dwlineid = Mxl.dwlineid;            The sound card audio output line ID obtained above//control type is control volume Mxlc.dwcontroltype = mixercontrol_controltype_volume;          Mxlc.ccontrols = 1;        Use mixercontrol struct variable number Mxlc.pamxctrl = &mxc; Mixercontrol struct variable pointer mxlc.cbmxctrl = sizeof (MXC); Mixercontrol structure variable byte size//Get controller information rc = Mixergetlinecontrols ((hmixerobj) hmixer, &am            P;MXLC, Mixer_getlinecontrolsf_onebytype); If the controller information is obtained successfully, then if (mmsyserr_noerror = = RC) {//Gets the volume range of the value in the controller: MXC. Bounds.lminimum to Mxc.bounds.Lmaximum.      Mixercontroldetails Mxcd; The state information of the controller mixercontroldetails_signed volstruct;                Volume structure variable (for one Member)//mixercontroldetails structure variable clear 0 zeromemory (&mxcd, sizeof (MXCD));       mxcd.cbstruct = sizeof (MXCD); Microsoft uses this method to judge version mxcd.dwcontrolid = Mxc.dwcontrolid;        The controller ID obtained above mxcd.padetails = &volStruct; Volume structure body variable pointer mxcd.cbdetails = sizeof (volstruct);                 Volume structure body variable byte size mxcd.cchannels = 1; Get or set all channels//Gets the volume range of the values in the controller: MXC. Bounds.lminimum to Mxc.Bounds.lMaximum.//Get volume value rc = Mixergetcontroldetails ((hmixerobj) hmixer                , &mxcd, Mixer_getcontroldetailsf_value); if (mmsyserr_noerror = = RC) {Long step = (MXC. Bounds.lmaximum-mxc.                   bounds.lminimum)/100; <span style= "color:#ff6666; " > volstruct.lvalue = volumnindex*step;                          The value you want to set rc = Mixersetcontroldetails ((hmixerobj) hmixer, &mxcd,  Mixer_setcontroldetailsf_value);                    </span> if (mmsyserr_noerror = = RC) {return 1; }                  }            }        }    }}



Get and set audio device volume under Windows system

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.