Exemple #1
0
 public void Start()
 {
     lock (mutex)
     {
         if (!isInited)
         {
             throw new InvalidOperationException("Not initialized - call Setup first");
         }
         if (isStarted)
         {
             return;
         }
         int hr = audioClient.Start();
         if (hr != 0)
         {
             Marshal.ThrowExceptionForHR(hr);
         }
         samplesRead         = 0;
         samplesWritten      = 0;
         thread              = new Thread(RunThread);
         thread.IsBackground = true;
         thread.Priority     = ThreadPriority.AboveNormal;
         thread.Start();
         isStarted = true;
     }
 }
        /// <summary>
        /// The Initialize Audio Client
        /// </summary>
        /// <param name="audioFlow"></param>
        /// <param name="_deviceEnumerator"></param>
        private void InitializeAudioClient()
        {
            //Get Audio Client from device
            COMResult result = _audioDevice.Activate(typeof(IAudioClient).GUID, 0, IntPtr.Zero, out object obj);

            _audioClient = (IAudioClient)obj;
            //Get Audio Meter from device
            result      = _audioDevice.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero, out obj);
            _audioMeter = (IAudioMeterInformation)obj;
            //Get Audio End Point
            result = _audioDevice.Activate(typeof(IAudioEndpointVolume).GUID, 0, IntPtr.Zero, out obj);
            _audioEndpointVolume = (IAudioEndpointVolume)obj;
            _audioEndpointVolume.RegisterControlChangeNotify(classCallBack);
            //Initialize Audio Client.
            _sessionGuid = new Guid();
            result       = _audioClient.GetMixFormat(out waveFormat);
            AudioClientStreamFlags streamFlag = AudioClientStreamFlags.None;

            if (_audioDataFlow == AudioDataFlow.eRender)
            {
                streamFlag = AudioClientStreamFlags.Loopback;
            }
            result = _audioClient.Initialize(AudioClientMode.Shared, streamFlag, 10000000, 0, waveFormat, ref _sessionGuid);
            result = _audioClient.Start();
            //Change wave format here
            SetupWaveFormat(waveFormat);

            result = _audioEndpointVolume.GetChannelCount(out _channelCount);
        }
        private void InitializeAudio(AudioDataFlow audioFlow, IMMDeviceEnumerator deviceEnumerator)
        {
            //Get Audio Device
            COMResult result = deviceEnumerator.GetDefaultAudioEndpoint(audioFlow, EndPointRole.eMultimedia, out _audioDevice);

            //Register End point notification
            _notifyClient = new MMNotificationClient();
            result        = deviceEnumerator.RegisterEndpointNotificationCallback(_notifyClient);
            //Get Audio Client from device
            result       = _audioDevice.Activate(typeof(IAudioClient).GUID, 0, IntPtr.Zero, out object obj);
            _audioClient = (IAudioClient)obj;
            //Get Audio Meter from device
            result      = _audioDevice.Activate(typeof(IAudioMeterInformation).GUID, 0, IntPtr.Zero, out obj);
            _audioMeter = (IAudioMeterInformation)obj;
            //Initialize Audio Client.
            _sessionGuid = new Guid();
            result       = _audioClient.GetMixFormat(out waveFormat);
            AudioClientStreamFlags streamFlag = AudioClientStreamFlags.None;

            if (audioFlow == AudioDataFlow.eRender)
            {
                streamFlag = AudioClientStreamFlags.Loopback;
            }
            result = _audioClient.Initialize(AudioClientMode.Shared, streamFlag, 10000000, 0, waveFormat, ref _sessionGuid);
            //Get Capture Client.
            result = _audioClient.GetService(typeof(IAudioCaptureClient).GUID, out obj);
            Marshal.ThrowExceptionForHR((int)result);
            _audioCaptureClient = (IAudioCaptureClient)obj;
            result = _audioClient.Start();
            //Change wave format here
            SetupWaveFormat(waveFormat);
        }
Exemple #4
0
 public void Start()
 {
     if (!_isStarted)
     {
         Marshal.ThrowExceptionForHR(_RealClient.Start());
     }
     _isStarted = true;
 }
Exemple #5
0
        public void Start()
        {
            Initialized = true;
            int error = AudioClient.Start();

            if (error != 0)
            {
                Win32Platform.CheckError($"Couldn't start a layer context of device {Parent.Name}.", true);
            }
            Started = true;
        }
 /// <summary>
 /// Starts the audio stream
 /// </summary>
 public void Start()
 {
     try
     {
         audioClientInterface.Start();
     }
     catch (COMException ex)
     {
         FeenPhone.Audio.AudioEvents.InvokeOnAudioDeviceException(this, ex);
         throw;
     }
 }
Exemple #7
0
        public override void Start()
        {
            lock (this)
            {
                IntPtr pBuffer;
                int    count = _Stream.Read(_FullBuffer, 0, (int)_BufferFrameCount * _FrameSize);
                Console.WriteLine(count / _FrameSize);

                if (count > 0)
                {
                    _IAudioRenderClient.GetBuffer(count / _FrameSize, out pBuffer);
                    System.Runtime.InteropServices.Marshal.Copy(_FullBuffer, 0, pBuffer, count);
                    _IAudioRenderClient.ReleaseBuffer(count / _FrameSize, 0);
                }
                _IAudioClient.Start();
                _Thread.Start();
            }
        }
Exemple #8
0
        private void StartSilenceGeneration()
        {
            IntPtr mixFormatPtr = IntPtr.Zero;

            try
            {
                Checked(_endpoint.Activate(ref IAudioClientId, ClsCtxEnum.All, IntPtr.Zero, out var obj), "Silence.Activate");
                _audioClientForRendering = (IAudioClient)obj;

                Checked(_audioClientForRendering.GetMixFormat(out mixFormatPtr), "Silence.GetMixFormat");
                WaveFormatEx format = (WaveFormatEx)Marshal.PtrToStructure(mixFormatPtr, typeof(WaveFormatEx));

                CheckFormat(format);

                Checked(_audioClientForRendering.Initialize(AudioClientShareModeEnum.Shared, AudioClientStreamFlagsEnum.None, 10_000_000 * 5, 0, mixFormatPtr, Guid.Empty), "Silence.Initialize");
                Checked(_audioClientForRendering.GetBufferSize(out var bufferSize), "Silence.GetBufferSize");
                Checked(_audioClientForRendering.GetService(IAudioRenderClientId, out var renderObj), "Silence.GetService");

                _audioRenderClient = (IAudioRenderClient)renderObj;

                Checked(_audioClientForRendering.Start(), "Silence.Start");

                _silenceThread      = new Thread(() => SilenceGenerationRoutine(bufferSize, format));
                _silenceThread.Name = "Silence generator";
                _silenceThread.Start();
            }
            catch (Exception e)
            {
                ReleaseComObject(ref _audioClientForRendering);
                ReleaseComObject(ref _audioRenderClient);
                Core.LogError(e, "Faied to StartSilenceGeneration");
            }
            finally
            {
                if (mixFormatPtr != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(mixFormatPtr);
                }
            }
        }
Exemple #9
0
 /// <summary>
 /// Starts the audio stream
 /// </summary>
 public void Start()
 {
     audioClientInterface.Start();
 }
        public void recordingloop()
        {
            uint  packetLength;
            uint  numFramesAvailable;
            uint  flags;
            ulong junk1;
            ulong junk2;

            byte[]     pData;
            uint       AUDCLNT_BUFFERFLAGS_SILENT = 2;
            uint       bytespersample             = (uint)(waveformat.nChannels * waveformat.wBitsPerSample / 8);
            WaveFormat _wf        = new WaveFormat((int)waveformat.nSamplesPerSec, (int)waveformat.wBitsPerSample, (int)waveformat.nChannels);
            BE_CONFIG  _mp3config = new BE_CONFIG(_wf);
            Mp3Writer  _mp3writer = new Mp3Writer(memStream, _wf, _mp3config);

            int retVal = iAudioClient.Start();

            if (retVal != 0)
            {
                throw new Exception("IAudioClient.Start()");
            }
            keepgoing = true;
            while (keepgoing)
            {
                Thread.Sleep((int)(hnsActualDuration / 5000));
                retVal = iAudioCaptureClient.GetNextPacketSize(out packetLength);
                if (retVal != 0)
                {
                    throw new Exception("iAudioCaptureClient.GetNextPacketSize()");
                }
                while (packetLength != 0)
                {
                    IntPtr dataPtr = IntPtr.Zero;
                    retVal = iAudioCaptureClient.GetBuffer(out dataPtr, out numFramesAvailable, out flags, out junk1, out junk2);
                    if (retVal != 0)
                    {
                        throw new Exception("iAudioCaptureClient.GetBuffer()");
                    }
                    pData = new byte[bytespersample * numFramesAvailable];
                    if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0)
                    {
                        for (int i = 0; i < pData.Length; i++)
                        {
                            pData[i] = 0;
                        }
                    }
                    else
                    {
                        Marshal.Copy(dataPtr, pData, 0, (int)(bytespersample * numFramesAvailable));
                    }
                    retVal = iAudioCaptureClient.ReleaseBuffer(numFramesAvailable);
                    if (retVal != 0)
                    {
                        throw new Exception("iAudioCaptureClient.ReleaseBuffer()");
                    }

                    lock (synclock)
                    {
                        _mp3writer.Write(pData, 0, pData.Length);
                    }
                    if (notify != null)
                    {
                        notify();
                    }

                    retVal = iAudioCaptureClient.GetNextPacketSize(out packetLength);
                    if (retVal != 0)
                    {
                        throw new Exception("iAudioCaptureClient.GetNextPacketSize()");
                    }
                }
            }
            _mp3writer.Close();
            memStream.Close();
            memStream.Dispose();
            if (iAudioClient != null)
            {
                retVal = iAudioClient.Stop();
                if (retVal != 0)
                {
                    throw new Exception("iAudioClient.Stop()");
                }
            }
        }
Exemple #11
0
        /*
         * [PreserveSig]
         * int GetMixFormat([Out] out WaveFormatExtensible format);
         */

        public void Start()
        {
            _realAudioClient.Start();
        }
Exemple #12
0
        public WaveFormatEx Open()
        {
            StopSilenceThread();

            Log.Information("Opening DesktopAudio");
            IMMDeviceEnumerator deviceEnumerator = null;
            IntPtr mixFormatPtr = IntPtr.Zero;

            try
            {
                bool render = true;
                deviceEnumerator = Activator.CreateInstance(typeof(MMDeviceEnumerator)) as IMMDeviceEnumerator;
                var res = deviceEnumerator.GetDefaultAudioEndpoint(
                    render ? DataFlowEnum.Render : DataFlowEnum.Capture,
                    render ? RoleEnum.Console : RoleEnum.Communications,
                    out _endpoint);

                if (render)
                {
                    StartSilenceGeneration();
                }

                Checked(_endpoint.Activate(ref IAudioClientId, ClsCtxEnum.All, IntPtr.Zero, out var obj), "Activate");
                _audioClient = (IAudioClient)obj;

                Checked(_audioClient.GetMixFormat(out mixFormatPtr), "GetMixFormat");
                WaveFormatEx outputFormat = (WaveFormatEx)Marshal.PtrToStructure(mixFormatPtr, typeof(WaveFormatEx));

                if (!render) // for render it is checked in the StartSilenceGeneration();
                {
                    CheckFormat(outputFormat);
                }

                _bytesPerFrame = outputFormat.BlockAlign;

                var flags = AudioClientStreamFlagsEnum.StreamFlagsEventCallback | (render ? AudioClientStreamFlagsEnum.StreamFlagsLoopback : AudioClientStreamFlagsEnum.None);
                Checked(_audioClient.Initialize(AudioClientShareModeEnum.Shared, flags, 10_000_000 * 5, 0, mixFormatPtr, Guid.Empty), "Initialize");

                Checked(_audioClient.GetService(IAudioCaptureClientId, out var captureObj), "GetService");
                _audioCaptureClient = (IAudioCaptureClient)captureObj;

#pragma warning disable CS0618 // Type or member is obsolete
                Checked(_audioClient.SetEventHandle(_dataAvailable.Handle), "SetEventHandle");
#pragma warning restore CS0618 // Type or member is obsolete
                Checked(_audioClient.Start(), "Start");

                return(outputFormat);
            }
            catch (Exception e)
            {
                Core.LogError(e, "Open desktop audio failed");
                StopSilenceThread();

                ReleaseComFields();
                throw;
            }
            finally
            {
                if (mixFormatPtr != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(mixFormatPtr);
                }

                ReleaseComObject(ref deviceEnumerator);
            }
        }