示例#1
0
        public IStreamAudioSource GetStreamAudioSource(AudioDevice device)
        {
            var naudioDevice = NAudioUtilities.GetDevice(device);

            if (naudioDevice == null)
            {
                //no device found
                return(null);
            }

            //try WASAPI first
            var wasapiSource = ServiceProvider.GetService(typeof(NAudioWasapiStreamAudioSource)) as NAudioWasapiStreamAudioSource;

            if (wasapiSource != null)
            {
                //WASAPI is available
                try
                {
                    wasapiSource.SetAudioDevice(device);
                    return(wasapiSource);
                }
                catch (Exception e)
                {
                    //not supported?
                    Logger.LogError(e, "Could not initialize NAudio WASAPI source");
                    wasapiSource.Dispose();
                }
            }

            return(null);
        }
        /// <summary>
        /// Initializes this audio source with the given audio device. <see cref="Start"/> may be called afterwards.
        /// </summary>
        /// <param name="device"></param>
        public void SetAudioDevice(AudioDevice device)
        {
            this.Device = device;

            var naudioDevice = NAudioUtilities.GetDevice(device);

            if (naudioDevice.DataFlow == DataFlow.Capture)
            {
                this.Capture = new WasapiCapture(naudioDevice);
            }
            else
            {
                this.Capture = new WasapiLoopbackCapture(naudioDevice);
            }
            this.Format = NAudioUtilities.FromNAudioWaveFormat(this.Capture.WaveFormat);

            //set up event listeners
            this.Capture.DataAvailable += (s, e) =>
            {
                if (e.BytesRecorded == 0)
                {
                    return;
                }

                this.DataAvailable?.Invoke(this, new StreamAudioSourceDataEvent()
                {
                    Buffer = new ArraySegment <byte>(e.Buffer, 0, e.BytesRecorded),
                    Format = Format
                });
            };

            this.Capture.RecordingStopped += (s, e) =>
            {
                var cause = StreamAudioSourceStoppedCause.Unknown;
                if (StopRequested)
                {
                    cause = StreamAudioSourceStoppedCause.Stopped;
                }
                else if (e.Exception != null)
                {
                    cause = StreamAudioSourceStoppedCause.Exception;
                }

                this.Stopped?.Invoke(this, new StreamAudioSourceStoppedEvent()
                {
                    Cause     = cause,
                    Exception = e.Exception
                });
            };
        }