audio_capturer.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #include "audio_capturer.h"
  2. #include "basic/basic.h"
  3. #define DEFAULT_SAMPLE_RATE 48000 // 默认采样率:48kHz
  4. #define DEFAULT_BITS_PER_SAMPLE 16 // 默认位深:16bit
  5. #define DEFAULT_CHANNELS 1 // 默认音频通道数:1
  6. #define DEFAULT_AUDIO_PACKET_INTERVAL 10 // 默认音频包发送间隔:10ms
  7. bool AudioCapturer::Init(Type deviceType, CallBack callback, void* userInfo)
  8. {
  9. Stop();
  10. _userInfo = userInfo;
  11. _callback = callback;
  12. _deviceType = deviceType;
  13. __CheckBool(_CreateDeviceEnumerator(&_pDeviceEnumerator));
  14. __CheckBool(_CreateDevice(_pDeviceEnumerator, &_pDevice));
  15. __CheckBool(_CreateAudioClient(_pDevice, &_pAudioClient));
  16. if (!_IsFormatSupported(_pAudioClient)) {
  17. __CheckBool(_GetPreferFormat(_pAudioClient, &_formatex));
  18. }
  19. __CheckBool(_InitAudioClient(_pAudioClient, &_formatex));
  20. __CheckBool(_CreateAudioCaptureClient(_pAudioClient, &_pAudioCaptureClient));
  21. _isInit = true;
  22. return true;
  23. }
  24. bool AudioCapturer::Start()
  25. {
  26. __CheckBool(_isInit);
  27. _loopFlag = true;
  28. // 用于强制打开扬声器
  29. PlaySoundA("./rc/mute.wav", nullptr, SND_FILENAME | SND_ASYNC | SND_LOOP);
  30. _captureThread = new std::thread(
  31. [this] { _ThreadRun(_pAudioClient, _pAudioCaptureClient); });
  32. return true;
  33. }
  34. void AudioCapturer::Stop()
  35. {
  36. // CoUninitialize();
  37. _isInit = false;
  38. _loopFlag = false;
  39. Free(_captureThread, [this] {
  40. _captureThread->join();
  41. delete _captureThread;
  42. });
  43. Free(_pAudioCaptureClient, [this] { _pAudioCaptureClient->Release(); });
  44. if (_pAudioClient != nullptr) {
  45. _pAudioClient->Stop();
  46. }
  47. PlaySoundA(nullptr, nullptr, SND_FILENAME | SND_ASYNC | SND_LOOP);
  48. Free(_pAudioClient, [this] { _pAudioClient->Release(); });
  49. Free(_pDevice, [this] { _pDevice->Release(); });
  50. Free(_pDeviceEnumerator, [this] { _pDeviceEnumerator->Release(); });
  51. }
  52. bool AudioCapturer::_CreateDeviceEnumerator(IMMDeviceEnumerator** enumerator)
  53. {
  54. // __CheckBool(SUCCEEDED(CoInitializeEx(nullptr, COINIT_MULTITHREADED)));
  55. // __CheckBool(SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED)));
  56. __CheckBool(SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL,
  57. __uuidof(IMMDeviceEnumerator),
  58. reinterpret_cast<void**>(enumerator))));
  59. return true;
  60. }
  61. bool AudioCapturer::_CreateDevice(IMMDeviceEnumerator* enumerator, IMMDevice** device)
  62. {
  63. EDataFlow enDataFlow = _deviceType == Microphone ? eCapture : eRender;
  64. ERole enRole = eConsole;
  65. __CheckBool(SUCCEEDED(enumerator->GetDefaultAudioEndpoint(enDataFlow, enRole, device)));
  66. return true;
  67. }
  68. bool AudioCapturer::_CreateAudioClient(IMMDevice* device, IAudioClient** audioClient)
  69. {
  70. __CheckBool(SUCCEEDED(device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL,
  71. (void**)audioClient)));
  72. return true;
  73. }
  74. bool AudioCapturer::_IsFormatSupported(IAudioClient* audioClient)
  75. {
  76. memset(&_formatex, 0, sizeof(_formatex));
  77. WAVEFORMATEX* format = &_formatex.Format;
  78. format->nSamplesPerSec = DEFAULT_SAMPLE_RATE;
  79. format->wBitsPerSample = DEFAULT_BITS_PER_SAMPLE;
  80. format->nChannels = DEFAULT_CHANNELS;
  81. WAVEFORMATEX* closestMatch = nullptr;
  82. HRESULT hr = audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED,
  83. format, &closestMatch);
  84. if (hr == AUDCLNT_E_UNSUPPORTED_FORMAT) // 0x88890008
  85. {
  86. if (closestMatch == nullptr) // 如果找不到最相近的格式,closestMatch可能为nullptr
  87. {
  88. return false;
  89. }
  90. format->nSamplesPerSec = closestMatch->nSamplesPerSec;
  91. format->wBitsPerSample = closestMatch->wBitsPerSample;
  92. format->nChannels = closestMatch->nChannels;
  93. return true;
  94. }
  95. return false;
  96. }
  97. bool AudioCapturer::_GetPreferFormat(IAudioClient* audioClient,
  98. WAVEFORMATEXTENSIBLE* formatex)
  99. {
  100. WAVEFORMATEX* format = nullptr;
  101. __CheckBool(SUCCEEDED(audioClient->GetMixFormat(&format)));
  102. formatex->Format.nSamplesPerSec = format->nSamplesPerSec;
  103. formatex->Format.wBitsPerSample = format->wBitsPerSample;
  104. formatex->Format.nChannels = format->nChannels;
  105. return true;
  106. }
  107. bool AudioCapturer::_InitAudioClient(IAudioClient* audioClient,
  108. WAVEFORMATEXTENSIBLE* formatex)
  109. {
  110. AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED; // share Audio Engine with other applications
  111. DWORD streamFlags = _deviceType == Microphone ? 0 : AUDCLNT_STREAMFLAGS_LOOPBACK;
  112. streamFlags |= AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM; // A channel matrixer and a sample
  113. // rate converter are inserted
  114. streamFlags |= AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY; // a sample rate converter
  115. // with better quality than
  116. // the default conversion but
  117. // with a higher performance
  118. // cost is used
  119. REFERENCE_TIME hnsBufferDuration = 0;
  120. WAVEFORMATEX* format = &formatex->Format;
  121. format->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  122. format->nBlockAlign = (format->wBitsPerSample >> 3) * format->nChannels;
  123. format->nAvgBytesPerSec = format->nBlockAlign * format->nSamplesPerSec;
  124. format->cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
  125. formatex->Samples.wValidBitsPerSample = format->wBitsPerSample;
  126. formatex->dwChannelMask = format->nChannels == 1 ? KSAUDIO_SPEAKER_MONO : KSAUDIO_SPEAKER_STEREO;
  127. formatex->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  128. __CheckBool(SUCCEEDED(audioClient->Initialize(shareMode, streamFlags, hnsBufferDuration, 0,
  129. format, nullptr)));
  130. return true;
  131. }
  132. bool AudioCapturer::_CreateAudioCaptureClient(IAudioClient* audioClient,
  133. IAudioCaptureClient** audioCaptureClient)
  134. {
  135. __CheckBool(SUCCEEDED(audioClient->GetService(IID_PPV_ARGS(audioCaptureClient))));
  136. return true;
  137. }
  138. bool AudioCapturer::_ThreadRun(IAudioClient* audio_client,
  139. IAudioCaptureClient* audio_capture_client)
  140. {
  141. UINT32 num_success = 0;
  142. BYTE* p_audio_data = nullptr;
  143. UINT32 num_frames_to_read = 0;
  144. DWORD dw_flag = 0;
  145. UINT32 num_frames_in_next_packet = 0;
  146. audio_client->Start();
  147. while (_loopFlag) {
  148. SleepMs(5);
  149. while (true) {
  150. __CheckBool(SUCCEEDED(audio_capture_client->GetNextPacketSize(&num_frames_in_next_packet)));
  151. if (num_frames_in_next_packet == 0) {
  152. break;
  153. }
  154. __CheckBool(SUCCEEDED(audio_capture_client->GetBuffer(&p_audio_data, &num_frames_to_read,
  155. &dw_flag, nullptr, nullptr)));
  156. size_t size = (_formatex.Format.wBitsPerSample >> 3) * _formatex.Format.nChannels * num_frames_to_read;
  157. _callback(p_audio_data, size, _userInfo);
  158. __CheckBool(SUCCEEDED(audio_capture_client->ReleaseBuffer(num_frames_to_read)));
  159. }
  160. }
  161. audio_client->Stop();
  162. return true;
  163. }