问题
I am using the Windows waveOut API (aka MME or Multimedia Extension) mmsystem.h. Some programs change the audio playback sample rate (eg. from 44.1kHz to 48kHz), and it would be very useful for my program to detect the current playback sample rate, so it can warn users that Windows will be resampling the program's output.
According to this documentation http://msdn.microsoft.com/en-us/library/aa909811.aspx, waveOutGetPlaybackRate returns the resampling % that the device is currently performing (eg, device plays at 44.1, and program is playing audio at 44.1 so it would return 1.0). I am curious if there is a way to get the absolute sample rate of the device, rather than something relative. In Windows Vista/7/8 you would manually find this value by going to: Control Panel > Sound > Playback, right-click on default playback device and choose Properties, and choose Advanced tab. So I am trying to get this "default format" value found here, by querying the OS.
The program in question is written in Pascal, however, I usually use C/C++ references.
回答1:
//#include <iostream>
//#include <initguid.h>
//#include <Mmdeviceapi.h>
int main() {
HRESULT hr;
IMMDevice * pDevice = NULL;
IMMDeviceEnumerator * pEnumerator = NULL;
IPropertyStore* store = nullptr;
PWAVEFORMATEX deviceFormatProperties;
PROPVARIANT prop;
CoInitialize(NULL);
// get the device enumerator
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (LPVOID *)&pEnumerator);
// get default audio endpoint
hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDevice);
hr = pDevice->OpenPropertyStore(STGM_READ, &store);
if (FAILED(hr)) {
std::cout << "OpenPropertyStore failed!" << std::endl;
}
hr = store->GetValue(PKEY_AudioEngine_DeviceFormat, &prop);
if (FAILED(hr)) {
std::cout << "GetValue failed!" << std::endl;
}
deviceFormatProperties = (PWAVEFORMATEX)prop.blob.pBlobData;
std::cout << "Channels = " << deviceFormatProperties->nChannels << std::endl;
std::cout << "Sample rate = " << deviceFormatProperties->nSamplesPerSec << std::endl;
std::cout << "Bit depth = " << deviceFormatProperties->wBitsPerSample << std::endl;
system("pause");
return 0;
}
来源:https://stackoverflow.com/questions/26286131/how-do-you-get-the-current-sample-rate-of-windows-audio-playback