QA: How can I change sound volume from my program?
Vassili Philippov (vasja@spbteam.com), October 02, 2001.
Question
I need to change sound volume from my program. It could be changed
in the Control Panel in Sounds & Reminders applet but I need to change
sound from my program. How can I do it?
Answer
Although there is a registry key (HKEY_CURRENT_USER\ControlPanel\Volume\Volume) that is changed every time
when sound volume setting in the Control Panel is changed it seems impossible
to change sound volume by changing this settings. I suggest another way for changing
sound volume. This way is using waveOutSetVolume function. If you change
sound volume using this function then settings in the Control Panel will not be changed
but actual sound volume will be changed.
Using waveOutSetVolume
waveOutSetVolume function sets volume of the certain waveform-audio output device.
If we assume that there is only one audio output device in our Pocket PC then it
is enough to find the first one and set sound volume for it. Volume can be in range
between 0 and 0xFFFF.
void SetSoundVolume(DWORD dwVolume) {
WAVEFORMATEX wf;
wf.wFormatTag = WAVE_FORMAT_PCM;
wf.nChannels = 1;
wf.nSamplesPerSec = 8000 * 1000;
wf.wBitsPerSample = 8;
wf.nBlockAlign = wf.nChannels * wf.wBitsPerSample / 8;
wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
wf.cbSize = 0;
HWAVEOUT hwo;
for (UINT id = 0; id < waveOutGetNumDevs(); id++) {
if (waveOutOpen(&hwo, id, &wf, 0, 0, CALLBACK_NULL)
== MMSYSERR_NOERROR)
{
waveOutSetVolume(hwo, dwVolume);
waveOutClose(hwo);
break;
}
}
}
Sound volume in percents
If you want to sound volume in percents instead of number between 0 and 0xFFFF then you can
use the following code for that:
DWORD dwSoundVolumePercents = 50;
SetSoundVolume( (DWORD)(0xFFFF*1.0*dwSoundVolumePercents/100.0) );
Related resources:
-
http://www.pocketpcdn.com/sections/audio.html
Section: Audio
-
http://www.pocketpcdn.com/articles/pocketpcaudio.html
Article: Playing audio on the Pocket PC
-
http://www.pocketpcdn.com/articles/playsound.html
Article: Play wav sound on Pocket PC
- http://samples.gotdotnet.com/quickstart/CompactFramework/doc/playsounds.aspx
Article: Interoperability with native code: Playing Sounds