|
- #include <iostream>
- #include <windows.h>
- #include <mmsystem.h>
- #pragma comment(lib, "winmm.lib")
- void CALLBACK waveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2) {
- if (uMsg == WIM_DATA) {
- WAVEHDR* header = (WAVEHDR*)dwParam1;
- short* buffer = (short*)header->lpData;
- int volume = 0;
- for (int i = 0; i < header->dwBytesRecorded / sizeof(short); i++) {
- volume += abs(buffer[i]);
- }
- volume /= (header->dwBytesRecorded / sizeof(short));
- std::cout << "音量: " << volume << std::endl;
- waveInAddBuffer(hwi, header, sizeof(WAVEHDR));
- }
- }
- int main() {
- WAVEFORMATEX format;
- format.wFormatTag = WAVE_FORMAT_PCM;
- format.nChannels = 1;
- format.nSamplesPerSec = 44100;
- format.wBitsPerSample = 16;
- format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8;
- format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
- format.cbSize = 0;
- HWAVEIN hwi;
- MMRESULT result = waveInOpen(&hwi, WAVE_MAPPER, &format, (DWORD_PTR)waveInProc, 0, CALLBACK_FUNCTION);
- if (result != MMSYSERR_NOERROR) {
- std::cerr << "无法打开音频输入设备" << std::endl;
- return 1;
- }
- WAVEHDR header;
- ZeroMemory(&header, sizeof(WAVEHDR));
- header.lpData = new char[format.nBlockAlign];
- header.dwBufferLength = format.nBlockAlign;
- header.dwFlags = WHDR_DONE;
- result = waveInPrepareHeader(hwi, &header, sizeof(WAVEHDR));
- if (result != MMSYSERR_NOERROR) {
- std::cerr << "无法准备音频输入头" << std::endl;
- return 1;
- }
- result = waveInAddBuffer(hwi, &header, sizeof(WAVEHDR));
- if (result != MMSYSERR_NOERROR) {
- std::cerr << "无法添加音频输入缓冲区" << std::endl;
- return 1;
- }
- result = waveInStart(hwi);
- if (result != MMSYSERR_NOERROR) {
- std::cerr << "无法开始音频输入" << std::endl;
- return 1;
- }
- MSG msg;
- while (GetMessage(&msg, NULL, 0, 0)) {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- waveInUnprepareHeader(hwi, &header, sizeof(WAVEHDR));
- delete[] header.lpData;
- waveInClose(hwi);
- return 0;
- }
复制代码 |
|