UE4 using WASAPI to get system audio

Source: Internet
Author: User

Multithreading +wasapi Get System audio:

#pragmaOnce#include"CoreMinimal.h"//multithread#include"Runnable.h"#include"RunnableThread.h"#include"ThreadSafeCounter.h"#include"ThreadSafeBool.h"structiaudioclient;structiaudiocaptureclient;typedef Longlong reference_time;typedefstructTwaveformatex WaveFormatEx;classTestjigou_api Audiostreamthread: Publicfrunnable{ Public: Audiostreamthread (); ~Audiostreamthread (); //pausing a thread    voidPausethread (); //Continue thread    voidContinuethread (); //stopping a thread    voidStopthread (); BOOListhreadpaused (); BOOListhreadkilled (); //transmitting audio data to Zego    voidCopydata2zego (unsignedChar* Data,intdatalen); Public: WaveFormatEx*M_format; //Audio Datatarray<unsignedChar>M_audiodata;Private: Frunnablethread*Thread;    Fthreadsafecounter Stoptaskcounter; Fcriticalsection M_mutex;Private:    intCurindex; //WASAPI Variableiaudioclient*m_client; Iaudiocaptureclient*m_capture;    Reference_time M_waittime; //WASAPI Function    voidSetwaveformat (waveformatex&format); BOOLInitloopback (); voidAudiostreamloop (); voidStopaudiostream ();Private:    //override function    Virtual BOOLInit ()Override; VirtualUInt32 Run ()Override; Virtual voidStop ()Override; Virtual voidExit ()Override;Private: Fthreadsafebool M_kill; Fthreadsafebool M_pause;};
#include"AudioStreamThread.h"#include"WindowsPlatformProcess.h"//WASAPI#include <mmdeviceapi.h>#include<AudioClient.h>Audiostreamthread::audiostreamthread () {M_kill=false; M_pause=false; M_client=nullptr; M_capture=nullptr; M_format=nullptr; Curindex=0; Thread= Frunnablethread::create ( This, TEXT ("Audiostreamthread"),0, tpri_normal);} Audiostreamthread::~Audiostreamthread () {if(Thread) {DeleteThread; Thread=nullptr; }}voidaudiostreamthread::P ausethread () {M_pause=true;}voidAudiostreamthread::continuethread () {M_pause=false;}voidAudiostreamthread::stopthread () {Stop (); if(thread) {thread-waitforcompletion (); }}BOOLaudiostreamthread::isthreadpaused () {return(BOOL) M_pause;}BOOLaudiostreamthread::isthreadkilled () {return(BOOL) M_kill;}voidAudiostreamthread::copydata2zego (unsignedChar* Data,intdatalen) {M_mutex.    Lock (); if(M_audiodata.num () >=datalen)        {memcpy (data, M_audiodata.getdata (), datalen); //Curindex + = Datalen;M_audiodata.removeat (0, Datalen); } M_mutex. Unlock ();}voidAudiostreamthread::setwaveformat (waveformatex&format) {    if(Format.wformattag = =wave_format_ieee_float) {Format.wformattag=WAVE_FORMAT_PCM; }    Else if(Format.wformattag = =wave_format_extensible) {pwaveformatextensible pEx= Reinterpret_cast<pwaveformatextensible> (&format); if(IsEqualGUID (Ksdataformat_subtype_ieee_float, pex->Subformat)) {pEx->subformat =KSDATAFORMAT_SUBTYPE_PCM; PEx->samples.wvalidbitspersample = -; }} format.wbitspersample= -; Format.nblockalign= Format.nchannels * Format.wbitspersample/8; Format.navgbytespersec= Format.nblockalign *format.nsamplespersec;}BOOLAudiostreamthread::initloopback () {Immdeviceenumerator*Enumerator; HRESULT HR= CoCreateInstance (__uuidof (Mmdeviceenumerator), NULL, Clsctx_inproc_server, __uuidof (Immdeviceenumerator), reinterpret_cast<void**> (&enumerator)); Immdevice*device; HR= Enumerator->getdefaultaudioendpoint (Erender, Econsole, &device); HR= Device->activate (__uuidof (iaudioclient), Clsctx_server, NULL, reinterpret_cast<void**> (&m_client)); HR= M_client->getmixformat (&M_format); Setwaveformat (*M_format); HR= M_client->initialize (audclnt_sharemode_shared, Audclnt_streamflags_loopback,0,0, M_format, NULL); HR= M_client->getservice (__uuidof (iaudiocaptureclient), reinterpret_cast<void**> (&m_capture)); HR= M_client->getdeviceperiod (&M_waittime, NULL); HR= m_client->Start (); if(Enumerator! =nullptr) {Enumerator-Release (); }    if(Device! =nullptr) {Device-Release (); }    returnsucceeded (HR);}voidAudiostreamthread::audiostreamloop () {BYTE* data =nullptr;    UINT32 size;    DWORD flags;    UINT64 device, performance; HRESULT HR= M_capture->getnextpacketsize (&size); HR= M_capture->getbuffer (&data, &size, &flags, &device, &performance); intBytewrite = size*m_format->nblockalign; if(Data! =nullptr)    {m_audiodata.append (data, size); } uint8_t* Formatdata = (uint8_t*) data; HR= m_capture->ReleaseBuffer (size);} voidAudiostreamthread::stopaudiostream () {}BOOLAudiostreamthread::init () {returninitloopback ();} UInt32 Audiostreamthread::run () {Fplatformprocess::sleep (0.03);  while(Stoptaskcounter.getvalue () = =0&&!M_kill) {        if(m_pause) {if(M_kill) {return 0; }        }        Else{M_mutex.            Lock (); //content that needs to be processed synchronously//Audiostreamloop ();byte* data =nullptr;            UINT32 size;            DWORD flags;            UINT64 device, performance; HRESULT HR= M_capture->getnextpacketsize (&size); HR= M_capture->getbuffer (&data, &size, &flags, &device, &performance); intBytewrite = size*m_format->nblockalign; if(Data! =nullptr)            {m_audiodata.append (data, bytewrite); } uint8_t* Formatdata = (uint8_t*) data; HR= m_capture->ReleaseBuffer (size); M_mutex.            Unlock (); Fplatformprocess::sleep ((m_waittime)/2/ (Ten* +) / +); }    }    return 0;}voidAudiostreamthread::stop () {stoptaskcounter.increment (); M_kill=true; M_pause=false;}voidaudiostreamthread::exit () {}

Audio data is stored in the M_audiodata, because it is real-time acquisition, where the corresponding length of data will be deleted, if you want to implement the recording function, instead of deleting the extracted data.

UE4 using WASAPI to get system audio

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.