Esempio n. 1
0
        private int GetBufferSize()
        {
            uint result;

            Marshal.ThrowExceptionForHR(_realAudioClient.GetBufferSize(out result));

            return((int)result);
        }
Esempio n. 2
0
 internal PlaybackClient_WindowsCoreApi(IAudioClient IAudioClient, System.IO.Stream Stream, int NumChannel, int FrameSize, uint SamplesRate, Type DataFormat)
 {
     _IAudioClient = IAudioClient;
     _IAudioClient.GetService(ref IID_IAudioRenderClient, out _IAudioRenderClient);
     _IAudioClient.GetBufferSize(out _BufferFrameCount);
     _Stream         = Stream;
     _FrameSize      = FrameSize;
     _BufferDuration = _BufferFrameCount / (SamplesRate / 1000);
     _FullBuffer     = new byte[_FrameSize * _BufferFrameCount];
     _Thread         = new System.Threading.Thread(Loop);
     _ChannelCount   = NumChannel;
     _SampleRate     = SamplesRate;
     _Format         = DataFormat;
 }
        private void AudioPluseMonitorWork()
        {
            uint bufferCount      = 0;
            int  packageSize      = -1;
            int  numberFramToRead = -1;
            long devicePosition   = 0;
            long qpcPosition      = 0;
            AudioClientBufferFlags bufferFlag;
            IntPtr packageBuffer = IntPtr.Zero;
            var    blockAlign    = waveFormat.NBlockAlign;
            var    result        = _audioClient.GetBufferSize(ref bufferCount);
            // Calculate the actual duration of the allocated buffer.
            var hnsActualDuration = (double)REFTIMES_PER_SEC *
                                    bufferCount / waveFormat.NSamplesPerSec;

            while (isAudioPluseMonitor)
            {
                Thread.Sleep((int)(hnsActualDuration / REFTIMES_PER_MILLISEC / 2));
                result = _audioCaptureClient.GetNextPacketSize(out packageSize);
                if (result == 0 && packageSize > 0)
                {
                    while (packageSize > 0)
                    {
                        _audioCaptureClient.GetBuffer(out packageBuffer, out numberFramToRead, out bufferFlag, out devicePosition, out qpcPosition);
                        if (0 == numberFramToRead)
                        {
                            continue;
                        }
                        long lBytesToWrite = numberFramToRead * blockAlign;

                        if (AudioClientBufferFlags.Silent == bufferFlag)
                        {
                            _audiopluseCallBack(0, 0);
                        }
                        else
                        {
                            var pkgData = StructureToByteArray(packageBuffer);
                            ComputeDo3Band(pkgData, lBytesToWrite, waveFormat);
                        }
                        _audioCaptureClient.ReleaseBuffer(numberFramToRead);
                        result = _audioCaptureClient.GetNextPacketSize(out packageSize);
                    }
                }
                else
                {
                    _audiopluseCallBack(0, 0);
                }
            }
        }
Esempio n. 4
0
        public CoreAudio(bool microphone = false)
        {
            const uint REFTIMES_PER_SEC     = 10000000;
            const uint CLSCTX_INPROC_SERVER = 1;
            Guid       clsid        = new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E");
            Guid       IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");

            oEnumerator = null;
            uint hResult = CoCreateInstance(ref clsid, null, CLSCTX_INPROC_SERVER, ref IID_IUnknown, out oEnumerator);

            if (hResult != 0 || oEnumerator == null)
            {
                throw new Exception("CoCreateInstance() pInvoke failed");
            }

            iMde = oEnumerator as IMMDeviceEnumerator;
            if (iMde == null)
            {
                throw new Exception("COM cast failed to IMMDeviceEnumerator");
            }

            IntPtr pDevice = IntPtr.Zero;

            //iMde.EnumAudioEndpoints(EDataFlow.eCapture, DEVICE_STATE_ACTIVE,ref pDevice);
            int retVal;

            if (microphone)
            {
                retVal = iMde.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eConsole, ref pDevice);
            }
            else
            {
                retVal = iMde.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, ref pDevice);
            }

            if (retVal != 0)
            {
                throw new Exception("IMMDeviceEnumerator.GetDefaultAudioEndpoint()");
            }
            //int dwStateMask = DEVICE_STATE_ACTIVE | DEVICE_STATE_NOTPRESENT | DEVICE_STATE_UNPLUGGED;
            //IntPtr pCollection = IntPtr.Zero;
            //retVal = iMde.EnumAudioEndpoints(EDataFlow.eRender, dwStateMask, ref pCollection);
            //if (retVal != 0)
            //{
            //    throw new Exception("IMMDeviceEnumerator.EnumAudioEndpoints()");
            //}
            imd = (IMMDevice)System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pDevice);
            if (imd == null)
            {
                throw new Exception("COM cast failed to IMMDevice");
            }

            Guid   iid               = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A");
            uint   dwClsCtx          = (uint)CLSCTX.CLSCTX_ALL;
            IntPtr pActivationParams = IntPtr.Zero;
            IntPtr pEndPoint         = IntPtr.Zero;

            retVal = imd.Activate(iid, dwClsCtx, pActivationParams, out pEndPoint);
            if (retVal != 0)
            {
                throw new Exception("IMMDevice.Activate()");
            }
            iAudioEndpoint = (IAudioEndpointVolume)System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pEndPoint);
            if (iAudioEndpoint == null)
            {
                throw new Exception("COM cast failed to IAudioEndpointVolume");
            }

            iid               = new Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2");
            dwClsCtx          = (uint)CLSCTX.CLSCTX_ALL;
            pActivationParams = IntPtr.Zero;
            pEndPoint         = IntPtr.Zero;
            retVal            = imd.Activate(iid, dwClsCtx, pActivationParams, out pEndPoint);
            if (retVal != 0)
            {
                throw new Exception("IAudioClient.Activate() " + Convert.ToString(retVal, 2));
            }

            iAudioClient = (IAudioClient)System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(pEndPoint);
            if (iAudioClient == null)
            {
                throw new Exception("COM cast failed to iAudioClient");
            }
            ulong processInterval;
            ulong minimumInterval;

            retVal = iAudioClient.GetDevicePeriod(out processInterval, out minimumInterval);
            if (retVal != 0)
            {
                throw new Exception("iAudioClient.GetDevicePeriod()");
            }

            waveformat                 = new WAVEFORMATEX();
            waveformat.wFormatTag      = (ushort)WaveFormatEncoding.Pcm;
            waveformat.nChannels       = 2;
            waveformat.nBlockAlign     = 4;
            waveformat.wBitsPerSample  = 16;
            waveformat.nSamplesPerSec  = 44100;
            waveformat.cbSize          = 0;
            waveformat.nAvgBytesPerSec = 176400;
            IntPtr reqForm = Marshal.AllocHGlobal(Marshal.SizeOf(waveformat));

            Marshal.StructureToPtr(waveformat, reqForm, false);

            IntPtr propForm = Marshal.AllocHGlobal(Marshal.SizeOf(waveformat));

            retVal = iAudioClient.IsFormatSupported(AUDCLNT_SHAREMODE.AUDCLNT_SHAREMODE_SHARED, reqForm, out propForm);
            if (retVal != 0)
            {
                throw new Exception("IAudioClient.IsFormatSupported()");
            }

            if (microphone)
            {
                retVal = iAudioClient.Initialize(AUDCLNT_SHAREMODE.AUDCLNT_SHAREMODE_EXCLUSIVE, 0, 2000000, 0, reqForm, Guid.Empty);
            }
            else
            {
                retVal = iAudioClient.Initialize(AUDCLNT_SHAREMODE.AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, 2000000, 0, reqForm, Guid.Empty);
            }

            if (retVal != 0)
            {
                throw new Exception("IAudioClient.Initialize() " + retVal);
            }
            uint buffersize = 0;

            retVal = iAudioClient.GetBufferSize(out buffersize);
            if (retVal != 0)
            {
                throw new Exception("IAudioClient.GetBufferSize()");
            }
            iid = new Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317");
            IntPtr capclient = IntPtr.Zero;

            retVal = iAudioClient.GetService(iid, out capclient);
            if (retVal != 0)
            {
                throw new Exception("IAudioClient.GetService()");
            }
            iAudioCaptureClient = (IAudioCaptureClient)System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(capclient);
            if (iAudioCaptureClient == null)
            {
                throw new Exception("COM cast failed to iAudioCaptureClient");
            }
            hnsActualDuration            = (double)(REFTIMES_PER_SEC * buffersize / waveformat.nSamplesPerSec); // 8391 smallest possible value
            recordingthread              = new Thread(recordingloop);
            recordingthread.IsBackground = false;
            recordingthread.Start();
        }
Esempio n. 5
0
 protected void InternalSetup(int dataFlow, int flags, int bufferSize = 0)
 {
     lock (mutex)
     {
         int hr; object obj; Guid guid;
         if (endpoint == null)
         {
             if (enumerator == null)
             {
                 enumerator = Activator.CreateInstance(typeof(MMDeviceEnumerator)) as IMMDeviceEnumerator;
                 if (enumerator == null)
                 {
                     throw new NotSupportedException();
                 }
             }
             hr = enumerator.GetDefaultAudioEndpoint((DataFlowEnum)dataFlow, RoleEnum.Multimedia, out endpoint);
             if (hr != 0)
             {
                 Marshal.ThrowExceptionForHR(hr);
             }
             if (endpoint == null)
             {
                 throw new NotSupportedException();
             }
         }
         if (audioClient != null)
         {
             Marshal.ReleaseComObject(audioClient); audioClient = null;
         }
         guid = IID_IAudioClient;
         hr   = endpoint.Activate(ref guid, ClsCtxEnum.ALL, IntPtr.Zero, out obj);
         if (hr != 0)
         {
             Marshal.ThrowExceptionForHR(hr);
         }
         audioClient = obj as IAudioClient;
         if (audioClient == null)
         {
             throw new NotSupportedException();
         }
         IntPtr mixFormatPtr = IntPtr.Zero;
         try
         {
             hr = audioClient.GetMixFormat(out mixFormatPtr);
             if (hr != 0)
             {
                 Marshal.ThrowExceptionForHR(hr);
             }
             WaveFormat outputFormat = (WaveFormat)Marshal.PtrToStructure(mixFormatPtr, typeof(WaveFormat));
             outputIsFloat = false;
             if (outputFormat.ExtraSize >= WaveFormatEx.WaveFormatExExtraSize)
             {
                 WaveFormatEx ex = (WaveFormatEx)Marshal.PtrToStructure(mixFormatPtr, typeof(WaveFormatEx));
                 if (ex.SubFormat == IeeeFloat)
                 {
                     outputIsFloat = true;
                 }
             }
             sampleRate    = outputFormat.SampleRate;
             channelCount  = outputFormat.Channels;
             bitsPerSample = outputFormat.BitsPerSample;
             if (bufferSize <= 0)
             {
                 bufferSize = 8192;
             }
             latencyMs = (int)(bufferSize * 500 / sampleRate);
             if (latencyMs <= 0)
             {
                 latencyMs = 1;
             }
             hr = audioClient.Initialize(AudioClientShareModeEnum.Shared, (AudioClientStreamFlagsEnum)flags,
                                         latencyMs * 40000, 0, mixFormatPtr, Guid.Empty);
             if (hr != 0)
             {
                 Marshal.ThrowExceptionForHR(hr);
             }
         }
         finally
         {
             if (mixFormatPtr != IntPtr.Zero)
             {
                 Marshal.FreeCoTaskMem(mixFormatPtr);
             }
         }
         hr = audioClient.GetBufferSize(out outputBufferSize);
         if (hr != 0)
         {
             Marshal.ThrowExceptionForHR(hr);
         }
         this.bufferSize = bufferSize;
         buffers         = new float[channelCount][];
         for (int i = 0; i < buffers.Length; i++)
         {
             buffers[i] = new float[bufferSize];
         }
         isInited = true;
     }
 }