控制音量
下面是通过调用Windows API控制音量递增的例子:
代码语言:javascript复制/**
@breif 修改Windows系统声音
*/
#include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#include <audioclient.h>
#include <iostream>
bool SetVolum(int volume)
{
HRESULT hr;
IMMDeviceEnumerator* pDeviceEnumerator = 0;
IMMDevice* pDevice = 0;
IAudioEndpointVolume* pAudioEndpointVolume = 0;
IAudioClient* pAudioClient = 0;
try {
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pDeviceEnumerator);
if (FAILED(hr)) throw "CoCreateInstance";
hr = pDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDevice);
if (FAILED(hr)) throw "GetDefaultAudioEndpoint";
hr = pDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, (void**)&pAudioEndpointVolume);
if (FAILED(hr)) throw "pDevice->Active";
hr = pDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&pAudioClient);
if (FAILED(hr)) throw "pDevice->Active";
float fVolume;
fVolume = volume / 100.0f;
hr = pAudioEndpointVolume->SetMasterVolumeLevelScalar(fVolume, &GUID_NULL);
if (FAILED(hr)) throw "SetMasterVolumeLevelScalar";
pAudioClient->Release();
pAudioEndpointVolume->Release();
pDevice->Release();
pDeviceEnumerator->Release();
return true;
}
catch (...) {
if (pAudioClient) pAudioClient->Release();
if (pAudioEndpointVolume) pAudioEndpointVolume->Release();
if (pDevice) pDevice->Release();
if (pDeviceEnumerator) pDeviceEnumerator->Release();
throw;
}
return false;
}
int main(int argc, char **argv)
{
CoInitialize(0);
int vol;
for (vol = 0; vol < 11; vol )
{
Sleep(1 * 1000);
SetVolum(vol);
std::cout << "已将音量调整至:" << vol << std::endl;
}
CoUninitialize();
return 0;
}
实际效果如下:
电脑音量从0到10递增,这里写的延时是1s。
播放音频
下面是通过Windows API播放音频的例子:
代码语言:javascript复制/*
C 播放音频(VS2017)
*/
#include <Windows.h>
#include <iostream>
#include <mmsystem.h> // 用于播放音频
#pragma comment(lib, "winmm.lib") // 导入声音头文件库
int main() {
std::cout << "开始播放音频……n";
mciSendString(TEXT("open ./sound/hello.mp3 alias mysong"), NULL, 0, NULL);
mciSendString(TEXT("play mysong"), NULL, 0, NULL);
Sleep(8000);
mciSendString(TEXT("close mysong"), NULL, 0, NULL);
system("pause");
return 0;
}
// 文字转语音 https://ttsmaker.com/zh-cn
实际效果如下:
电脑开始播放hello.mp3
的声音。
以上。