Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

audio - Is there a way in Java (+- JNA) to set the master system volume reliably in XP+Vista+Windows 7?

Appears that java's sound API's work well for single streams, and even for setting the input from the microphone, but not for setting the master volume level in Vista/Windows 7.

refs:

Java Sound API to access the system/master volume control in Vista and Win 7

How to adjust speaker volume from Java program?

Changing master volume level only works on XP for the master volume

Anybody have something that'll work for all of them (without compatibility mode or controlling the mouse to increase volume level [robot-like]).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have done my share of JNI and steer clear where I can. As long as you have to go native to accomplish something, and assuming the task is simple and performance isn't a major issue, I've found it a lot easier to launch a separate process than deal with JNI or any of its cousins. Here is some C++ code adapted from this article that will set the master volume based on a single command line parameter:

#include <WinSDKVer.h>
#define _WIN32_WINNT _WIN32_WINNT_VISTA
#include <SDKDDKVer.h>

#define WIN32_LEAN_AND_MEAN
// Windows Header Files:
#include <windows.h>
#include <tchar.h>

#include <mmdeviceapi.h>
#include <endpointvolume.h> 

int APIENTRY _tWinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPTSTR    lpCmdLine,
                 int       nCmdShow)
{
double newVolume = _ttof(lpCmdLine);

CoInitialize(NULL);

IMMDeviceEnumerator* deviceEnumerator = NULL;
if(CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID *)&deviceEnumerator) == S_OK) {
    IMMDevice* defaultDevice = NULL;
    if(deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice) == S_OK) {
        IAudioEndpointVolume* endpointVolume = NULL;
        if(defaultDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, (LPVOID *)&endpointVolume) == S_OK) {
            endpointVolume->SetMasterVolumeLevelScalar((float)newVolume, NULL);
            endpointVolume->Release();
        }
        defaultDevice->Release();
    }
    deviceEnumerator->Release();
}

CoUninitialize();

return 0;
}

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...