Ejemplo n.º 1
0
        /// <summary>
        /// 初始化录音设备,此处使用主录音设备.
        /// </summary>
        /// <returns>调用成功返回true,否则返回false</returns>
        private bool InitCaptureDevice()
        {
            // 获取默认音频捕捉设备
            AddLogInfo(DateTime.Now + "写入数据:获取默认音频捕捉设备 ");
            CaptureDevicesCollection devices = new CaptureDevicesCollection();  // 枚举音频捕捉设备

            Guid deviceGuid = Guid.Empty;                                       // 音频捕捉设备的ID

            if (devices.Count > 0)
            {
                deviceGuid = devices[0].DriverGuid;
                AddLogInfo(DateTime.Now + "写入数据:音频捕捉设备的ID" + deviceGuid);
            }
            else
            {
                AddLogInfo(DateTime.Now + "写入数据:系统中没有音频捕捉设备 ");
                //MessageBox.Show("系统中没有音频捕捉设备");
                return(false);
            }

            // 用指定的捕捉设备创建Capture对象
            try
            {
                mCapDev = new Capture(deviceGuid);
            }

            catch (DirectXException e)
            {
                AddLogInfo(DateTime.Now + "写入数据:" + e.Message.ToString());
                //MessageBox.Show(e.ToString());
                return(false);
            }

            return(true);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 初始化录音设备,此处使用主录音设备
        /// </summary>
        /// <returns>调用成功返回true,否则false</returns>
        bool InitCaptureDevice()
        {
            //获取默认的音频捕捉设备
            CaptureDevicesCollection devices = new CaptureDevicesCollection();
            Guid deviceGuid = Guid.Empty;

            if (devices.Count > 0)
            {
                deviceGuid = devices[0].DriverGuid;
            }
            else
            {
                MessageBox.Show("系统中没有音频捕捉设备");
                return(false);
            }
            // 用指定的捕捉设备创建Capture对象
            try
            {
                mCapDev = new Capture(deviceGuid);
            }
            catch (DirectXException e)
            {
                MessageBox.Show(e.ToString());
                return(false);
            }
            return(true);
        }
Ejemplo n.º 3
0
    public void SetVoiceDevices(int deviceID, short channels, short bitsPerSample, int samplesPerSecond)
    {
        // Установка голосовых устройств
        _device = new Device();                                                                   // Звуковое устройство ввода
        _device.SetCooperativeLevel(new System.Windows.Forms.Control(), CooperativeLevel.Normal); // Установить форму приложения и приоритет
        CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();        // Получить доступ к устройству (звуковая карта)
        DeviceInformation        deviceInfo = captureDeviceCollection[deviceID];                  // установить номер устройства

        _capture = new Capture(deviceInfo.DriverGuid);                                            //Получить информация о драйвере выбранного устройства

        //Настроить wave формат для захвата.
        _waveForm                       = new WaveFormat();                               // Объявление формата
        _waveForm.Channels              = channels;                                       // Каналы
        _waveForm.FormatTag             = WaveFormatTag.Pcm;                              // PCM - Pulse Code Modulation
        _waveForm.SamplesPerSecond      = samplesPerSecond;                               // установить число образцов в секунду
        _waveForm.BitsPerSample         = bitsPerSample;                                  // Установить колличество бит на образец
        _waveForm.BlockAlign            = (short)(channels * (bitsPerSample / (short)8)); // данных в одном байте,  1 * (16/8) = 2 bits
        _waveForm.AverageBytesPerSecond = _waveForm.BlockAlign * samplesPerSecond;        // байт в секунду  22050*2= 44100
        _capBufDescr                    = new CaptureBufferDescription();
        _capBufDescr.BufferBytes        = _waveForm.AverageBytesPerSecond / 5;            // 200 милисекунд для записи = 8820 бит
        _capBufDescr.Format             = _waveForm;                                      // Using Wave Format

        // воспроизведение
        _playbackBufferDescription             = new BufferDescription();
        _playbackBufferDescription.BufferBytes = _waveForm.AverageBytesPerSecond / 5;          // воспроизведение - 200 милисекунд = 8820 Bит
        _playbackBufferDescription.Format      = _waveForm;
        _playbackBuffer = new SecondaryBuffer(_playbackBufferDescription, _device);
        _bufferSize     = _capBufDescr.BufferBytes;
    }
Ejemplo n.º 4
0
        public void SetInputDevice()
        {
            CaptureDevicesCollection devices = new CaptureDevicesCollection();

            Microsoft.DirectX.DirectSound.Device mDevice = new Device(devices[Index].DriverGuid);
            mInputDevice = mDevice;
        }
Ejemplo n.º 5
0
        static void InicialiceCaptureBuffer()
        {
            try
            {
                CaptureDevicesCollection audioDevices = new CaptureDevicesCollection();

                // initialize the capture buffer and start the animation thread
                Capture cap = new Capture(audioDevices[1].DriverGuid);
                CaptureBufferDescription desc = new CaptureBufferDescription();
                WaveFormat wf = new WaveFormat();
                wf.BitsPerSample         = 16;
                wf.SamplesPerSecond      = 44100;
                wf.Channels              = (short)cap.Caps.Channels;
                wf.BlockAlign            = (short)(wf.Channels * wf.BitsPerSample / 8);
                wf.AverageBytesPerSecond = wf.BlockAlign * wf.SamplesPerSecond;
                wf.FormatTag             = WaveFormatTag.Pcm;

                desc.Format      = wf;
                desc.BufferBytes = SAMPLES * wf.BlockAlign;

                buffer = new CaptureBuffer(desc, cap);
                buffer.Start(true);
            }
            catch
            {
                Console.WriteLine("Error al iniciar el capturador de sonido");
            }
        }
Ejemplo n.º 6
0
        public static string[] EnumerateCaptureDevices()
        {
            // Get the Windows enumerated Capture devices adding a "-n" tag (-1, -2, etc.) if any duplicate names
            CaptureDevicesCollection cllCaptureDevices = new CaptureDevicesCollection();
            //DeviceInformation objDI = new DeviceInformation();
            int intCtr           = 0;
            int intDupeDeviceCnt = 0;

            string[] strCaptureDevices = new string[cllCaptureDevices.Count];
            foreach (DeviceInformation objDI in cllCaptureDevices)
            {
                DeviceDescription objDD = new DeviceDescription(objDI);
                strCaptureDevices[intCtr] = objDD.ToString().Trim();
                intCtr += 1;
            }

            for (int i = 0; i <= strCaptureDevices.Length - 1; i++)
            {
                intDupeDeviceCnt = 1;
                for (int j = i + 1; j <= strCaptureDevices.Length - 1; j++)
                {
                    if (strCaptureDevices[j] == strCaptureDevices[i])
                    {
                        intDupeDeviceCnt    += 1;
                        strCaptureDevices[j] = strCaptureDevices[i] + "-" + intDupeDeviceCnt.ToString();
                    }
                }
            }
            return(strCaptureDevices);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Create the capture device to use in the recording.
 /// </summary>
 public void createCaptureDevice()
 {
     // Just getting the first devoce for the moment - can change
     // latter if required.
     _device       = new CaptureDevicesCollection();
     captureDevice = new Capture(_device[0].DriverGuid);
 }
        private void UDP_Initialize()
        {
            try {
                device = new Device();
                device.SetCooperativeLevel(this, CooperativeLevel.Normal);

                CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

                DeviceInformation deviceInfo = captureDeviceCollection[0];

                capture = new Capture(deviceInfo.DriverGuid);

                short channels         = 1;     //Stereo.
                short bitsPerSample    = 16;    //16Bit, alternatively use 8Bits.
                int   samplesPerSecond = 22050; //11KHz use 11025 , 22KHz use 22050, 44KHz use 44100 etc.

                //Set up the wave format to be captured.
                waveFormat                       = new WaveFormat();
                waveFormat.Channels              = channels;
                waveFormat.FormatTag             = WaveFormatTag.Pcm;
                waveFormat.SamplesPerSecond      = samplesPerSecond;
                waveFormat.BitsPerSample         = bitsPerSample;
                waveFormat.BlockAlign            = (short)(channels * (bitsPerSample / (short)8));
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

                captureBufferDescription             = new CaptureBufferDescription();
                captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;//approx 200 milliseconds of PCM data.
                captureBufferDescription.Format      = waveFormat;

                playbackBufferDescription             = new BufferDescription();
                playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
                playbackBufferDescription.Format      = waveFormat;
                playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

                bufferSize = captureBufferDescription.BufferBytes;

                bIsCallActive  = false;
                nUdpClientFlag = 0;

                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint ourEP = new IPEndPoint(IPAddress.Any, 9450);
                //Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc).
                clientSocket.Bind(ourEP);

                //Receive data from any IP.
                EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));

                byteData = new byte[1024];
                //Receive data asynchornously.
                clientSocket.BeginReceiveFrom(byteData,
                                              0, byteData.Length,
                                              SocketFlags.None,
                                              ref remoteEP,
                                              new AsyncCallback(UDP_OnReceive),
                                              null);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "VoiceChat-Initialize ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 9
0
        public DeviceSelector()
        {
            InitializeComponent();

            //
            devices = new CaptureDevicesCollection();

            /*
             *          if(devices == null || devices.Count == 0)
             *          {
             *                  throw new ArgumentException("未偵測到任何音訊裝置!");
             *          }
             */

            if (devices.Count >= 1)
            {
                // devices[0] = "主要音效驅動程式"
                selectedDevice = devices[0];

                DeviceInformation info;
                for (int i = 0; i < devices.Count; i++)
                {
                    info = devices[i];
                    comboboxCaptureDeviceCombo.Items.Add(info.Description);
                }
                comboboxCaptureDeviceCombo.SelectedIndex = 0;
                selectedDevice = devices[comboboxCaptureDeviceCombo.SelectedIndex];
            }
        }
    public void SetVoiceDevices(int deviceID, short channels, short bitsPerSample, int samplesPerSecond)
    {
        // Installization Voice Devices
        device = new Device();                                                                   // Sound Input Device
        device.SetCooperativeLevel(new System.Windows.Forms.Control(), CooperativeLevel.Normal); // Set The Application Form and Priority
        CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();       // To Get Available Devices (Input Sound Card)
        DeviceInformation        deviceInfo = captureDeviceCollection[deviceID];                 // Set Device Number

        capture = new Capture(deviceInfo.DriverGuid);                                            // Get The Selected Device Driver Information

        //Set up the wave format to be captured.
        waveFormat                           = new WaveFormat();                               // Wave Format declaration
        waveFormat.Channels                  = channels;                                       // Channels  (2 if Stereo)
        waveFormat.FormatTag                 = WaveFormatTag.Pcm;                              // PCM - Pulse Code Modulation
        waveFormat.SamplesPerSecond          = samplesPerSecond;                               // The Number of Samples Peer One Second
        waveFormat.BitsPerSample             = bitsPerSample;                                  // The Number of bits for each sample
        waveFormat.BlockAlign                = (short)(channels * (bitsPerSample / (short)8)); // Minimum atomic unit of data in one byte, Ex: 1 * (16/8) = 2 bits
        waveFormat.AverageBytesPerSecond     = waveFormat.BlockAlign * samplesPerSecond;       // required Bytes-Peer-Second Ex. 22050*2= 44100
        captureBufferDescription             = new CaptureBufferDescription();
        captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;           //Ex. 200 milliseconds of PCM data = 8820 Bytes (In Record)
        captureBufferDescription.Format      = waveFormat;                                     // Using Wave Format

        // Playback
        playbackBufferDescription             = new BufferDescription();
        playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;          //Ex. 200 milliseconds of PCM data = 8820 Bytes (In Playback)
        playbackBufferDescription.Format      = waveFormat;
        playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
        bufferSize     = captureBufferDescription.BufferBytes;
    }
Ejemplo n.º 11
0
        /// <summary>
        /// 初始化录音设备,此处使用主录音设备.
        /// </summary>
        /// <returns>调用成功返回true,否则返回false</returns>
        private bool InitCaptureDevice()
        {
            // 获取默认音频捕捉设备
            CaptureDevicesCollection devices = new CaptureDevicesCollection(); // 枚举音频捕捉设备
            Guid deviceGuid = Guid.Empty;                                      // 音频捕捉设备的ID

            devList = new string[devices.Count];

            for (int i = 0; i < devices.Count; i++)
            {
                devList[i] = devices[i].Description.ToString();
            }

            if (devices.Count > 0)
            {
                deviceGuid = devices[1].DriverGuid;
            }
            else
            {
                MessageBox.Show("系统中没有音频捕捉设备");
                return(false);
            }

            // 用指定的捕捉设备创建Capture对象
            try
            {
                mCapDev = new Capture(deviceGuid);
            }
            catch (DirectXException e)
            {
                MessageBox.Show(e.ToString());
                return(false);
            }
            return(true);
        }
Ejemplo n.º 12
0
 private void ConfigurationDialog_Load(object sender, EventArgs e)
 {
     ConfSingleton settings = ConfSingleton.Instance;
     try
     {
         strategyDescription.Text = settings.Network.ToString();
     }
     catch (Exception ex)
     {
         strategyDescription.Text = ex.Message;
     }
     enableSoundEffectsCheckBox.Checked = settings.SoundEffects;
     multicastNetworkTextBox.Text = settings.MulticastNetworkStart;
     multiCastSubnetValue.Value = settings.MulticastPrefix;
     compressDecompressCheckBox.Checked = settings.Compression;
     multiCastSubnetValue.ValueChanged += new System.EventHandler(this.AddressChanged);
     multicastNetworkTextBox.TextChanged += new System.EventHandler(this.AddressChanged);
     CaptureDevicesCollection captureDevices = new CaptureDevicesCollection();
     for (int i = 0; i < captureDevices.Count; i++)
     {
         listBox1.Items.Add(captureDevices[i].Description);
         if (i.Equals(settings.CaptureDeviceIndex))
             listBox1.SelectedIndex = i;
     }
 }
Ejemplo n.º 13
0
        public static void SetVoiceDevices(int deviceID, short channels, short bitsPerSample, int samplesPerSecond)
        {
            device = new Device();
            device.SetCooperativeLevel(new System.Windows.Forms.Control(), CooperativeLevel.Normal);
            CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();
            DeviceInformation        deviceInfo = captureDeviceCollection[deviceID];

            capture = new Capture(deviceInfo.DriverGuid);

            waveFormat                           = new WaveFormat();
            waveFormat.Channels                  = channels;
            waveFormat.FormatTag                 = WaveFormatTag.Pcm;
            waveFormat.SamplesPerSecond          = samplesPerSecond;
            waveFormat.BitsPerSample             = bitsPerSample;
            waveFormat.BlockAlign                = (short)(channels * (bitsPerSample / (short)8));
            waveFormat.AverageBytesPerSecond     = waveFormat.BlockAlign * samplesPerSecond;
            captureBufferDescription             = new CaptureBufferDescription();
            captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
            captureBufferDescription.Format      = waveFormat;

            playbackBufferDescription             = new BufferDescription();
            playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
            playbackBufferDescription.Format      = waveFormat;
            playbackBufferDescription.GlobalFocus = true;
            playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
            bufferSize     = captureBufferDescription.BufferBytes;
        }
Ejemplo n.º 14
0
        private void PopformForScreenCap_Load(object sender, EventArgs e)//加载屏幕录制窗体
        {
            this.stopScreenCapBtn.Enabled = false;
            CaptureDevicesCollection sound_devices = new CaptureDevicesCollection();

            if (sound_devices.Count > 0)
            {
                int i = 0;
                while (i < sound_devices.Count)
                {
                    string text = sound_devices[i].Description;
                    if (text.Contains("麦克风"))
                    {
                        string descrip = sound_devices[i].Description;
                        int    len     = descrip.Length;
                        if (len > 31)
                        {
                            soundSource = descrip.Substring(0, 31);
                        }
                        else
                        {
                            soundSource = descrip;
                        }
                        this.soundChBox.Checked = true;
                        //return;
                        break;
                    }
                    i++;
                }
            }
        }
Ejemplo n.º 15
0
        public void StartRecording(int deviceIndex)
        {
            if (mCaptureBuffer != null)
            {
                if (mCaptureBuffer.Capturing)
                {
                    mCaptureBuffer.Stop();
                }

                mCaptureBuffer.Dispose();
                mCaptureBuffer = null;
            }

            CaptureDevicesCollection audioDevices = new CaptureDevicesCollection();

            if (deviceIndex != -1 && deviceIndex < audioDevices.Count - 1)
            {
                // initialize the capture buffer and start the animation thread
                Capture capture = new Capture(audioDevices[deviceIndex].DriverGuid);
                CaptureBufferDescription captureBufferDescription = new CaptureBufferDescription();
                WaveFormat waveFormat = new WaveFormat();
                waveFormat.BitsPerSample         = 16;
                waveFormat.SamplesPerSecond      = 8000;
                waveFormat.Channels              = 1;
                waveFormat.BlockAlign            = (short)(waveFormat.Channels * waveFormat.BitsPerSample / 8);
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * waveFormat.SamplesPerSecond;
                waveFormat.FormatTag             = WaveFormatTag.Pcm;

                captureBufferDescription.Format      = waveFormat;
                captureBufferDescription.BufferBytes = waveFormat.SamplesPerSecond * 120;

                mCaptureBuffer = new Microsoft.DirectX.DirectSound.CaptureBuffer(captureBufferDescription, capture);
                mCaptureBuffer.Start(true);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 初始化录音设备,此处使用主录音设备
        /// </summary>
        /// <returns>调用成功返回true,否则返回false</returns>
        private bool InitCaptureDevice()
        {
            // 获取默认音频捕捉设备
            CaptureDevicesCollection devices = new CaptureDevicesCollection();  // 枚举音频捕捉设备

            Guid deviceGuid = Guid.Empty;

            if (devices.Count > 0)
            {
                deviceGuid = devices[0].DriverGuid;
            }
            else
            {
                System.Windows.MessageBox.Show("No capture device !");

                return(false);
            }

            // 用指定的捕捉设备创建Capture对象
            try
            {
                mCapDev = new Capture(deviceGuid);
            }
            catch (DirectXException ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());

                return(false);
            }

            return(true);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 初始化录音设备,此处使用主录音设备.
        /// </summary>
        /// <returns>调用成功返回true,否则返回false</returns>
        bool InitCaptureDevice()
        {
            // 获取默认音频捕捉设备
            CaptureDevicesCollection devices = new CaptureDevicesCollection(); // 枚举音频捕捉设备
            Guid deviceGuid = Guid.Empty;                                      // 音频捕捉设备的ID

            if (devices.Count > 0)
            {
                deviceGuid = devices[0].DriverGuid;
            }

            else
            {
                Console.WriteLine("系统中没有音频捕捉设备");
                return(false);
            }

            // 用指定的捕捉设备创建Capture对象
            try
            {
                mCapDev = new Capture(deviceGuid);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
            }
            return(true);
        }
Ejemplo n.º 18
0
        private bool CreateSelectCaputerDevice(int i)
        {
            CaptureDevicesCollection capturedev = new CaptureDevicesCollection();
            Guid devguid = Guid.Empty;

            if (capturedev.Count > 0)
            {
                for (int j = 0; j < capturedev.Count; j++)
                {
                    if (sList[i] == capturedev[j].Description)
                    {
                        devguid = capturedev[j].DriverGuid;
                    }
                }
            }
            //Use the device GUID to create a capture device object
            if (devguid != Guid.Empty)
            {
                capture = new Capture(devguid);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 19
0
        public void SetInputDeviceForRecording(Control FormHandle, int Index)
        {
            CaptureDevicesCollection devices = new CaptureDevicesCollection();

            Microsoft.DirectX.DirectSound.Device mDevice = new  Microsoft.DirectX.DirectSound.Device(devices[Index].DriverGuid);
            mDevice.SetCooperativeLevel(FormHandle, CooperativeLevel.Priority);
            m_InputDevice = mDevice;
        }
Ejemplo n.º 20
0
        //returns the guid of the selected device, in this case the default
        //device guid has been returned
        public Guid SetInputDeviceGuid()
        {
            CaptureDevicesCollection devices = new CaptureDevicesCollection();

            m_aGuid = GetInputDevice();
            m_gCaptureDeviceGuid = devices[1].DriverGuid;
            return(m_gCaptureDeviceGuid);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Obtains a list of the audio input devices attached to the computer.
 /// </summary>
 /// 
 /// <remarks>
 /// Note that the collection is reobtained here everytime, on the quite
 /// possible event that, when prompted with a list of devices, a user plugs
 /// in a new device, and then reloads the list.
 /// </remarks>
 /// 
 /// <returns>The input devices found.</returns>
 public string[] GetAudioInputDeviceNames()
 {
     devices = new CaptureDevicesCollection();
       string[] names = new string[devices.Count];
       for (int i = 0; i < devices.Count; ++i) {
     names[i] = devices[i].Description;
       }
       return names;
 }
Ejemplo n.º 22
0
        public Capture InitDirectSound(int Index)
        {
            CaptureDevicesCollection devices = new CaptureDevicesCollection();
            Guid mGuid = Guid.Empty;

            mGuid = devices[Index].DriverGuid;
            m_cApplicationDevice = new Capture(mGuid);
            return(m_cApplicationDevice);
        }
Ejemplo n.º 23
0
        // returns a list of input devices
        public ArrayList GetInputDevice()
        {
            CaptureDevicesCollection devices = new CaptureDevicesCollection();              // gathers the available capture devices

            foreach (DeviceInformation info in devices)
            {
                m_aSelect.Add(info.Description);
            }
            return(m_aSelect);
        }
 public static SoundCaptureDevice[] GetDevices()
 {
     CaptureDevicesCollection captureDevices = new CaptureDevicesCollection();
     List<SoundCaptureDevice> devices = new List<SoundCaptureDevice>();
     foreach (DeviceInformation captureDevice in captureDevices)
     {
         devices.Add(new SoundCaptureDevice(captureDevice.DriverGuid, captureDevice.Description));
     }
     return devices.ToArray();
 }
Ejemplo n.º 25
0
        /// <summary>
        /// 音声処理管理部を作成する。
        /// </summary>
        /// <param name="id">この端末のID(どの端末が近くにいるのかの表示に利用)</param>
        /// <param name="sendBack">比較用データ取得deligate</param>
        /// <param name="sendInterval">近接センシング用データ送信周期(ミリ秒, 7000ms以下とする)</param>
        /// <param name="fftLength">比較をかけるサウンドデータのバイト数(32000/s)</param>
        /// <param name="proximityKeepCycle">一度のTrue判定が影響を及ぼす周期数</param>
        /// <param name="soundDirectory">音声ログ(16kbps, 16bit)保存のためのディレクトリ</param>
        /// <param name="errorFile">エラーログを書き出すファイル</param>
        public SoundControl(string id, SendBackSignalDelegate sendBack, int fftLength, int sendInterval, int proximityKeepCycle, string soundDirectory, string errorFile)
        {
            try
            {
                this.id           = id;
                SystemDirectory   = Path.Combine(soundDirectory, "system");
                LogFile           = Path.Combine(SystemDirectory, DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".log");
                diffTimeDictonary = new Dictionary <string, long>();

                sendBackDeligate            = sendBack;
                completeSendBack            = new AsyncCallback(CompleteSendBackMethod);
                SoundControl.soundDirectory = soundDirectory;
                SoundControl.errorFile      = errorFile;

                if (sendInterval > 7000)
                {
                    sendInterval = 7000;
                }
                CreateDirectory();
                this.sendInterval       = sendInterval;
                this.proximityKeepCycle = proximityKeepCycle;
                dataBuffer = new DataBuffer(this, fftLength);


                //音量の設定
                int mixer;
                Mixer.init(out mixer);                //Mixer初期化
                Mixer.SetMainVolume(mixer, 50);       //Mainのボリュームを50%に設定
                Mixer.SetWaveOutVolume(mixer, 50);    //WavOutを50%に設定
                Mixer.SetMicRecordVolume(mixer, 100); //マイク録音を100%に設定

                // デバイス初期化
                CaptureDevicesCollection devices = new CaptureDevicesCollection();
                applicationDevice = new Capture(devices[0].DriverGuid);
                if (applicationDevice != null)
                {
                    inputFormat = new WaveFormat();
                    inputFormat.BitsPerSample         = BitsPerSample;
                    inputFormat.Channels              = Channels;
                    inputFormat.SamplesPerSecond      = SamplesPerSec;
                    inputFormat.FormatTag             = WaveFormatTag.Pcm;
                    inputFormat.BlockAlign            = BlockAlign;
                    inputFormat.AverageBytesPerSecond = AvgBytesPerSec;

                    recordingThread = new Thread(new ThreadStart(RecordWorker));
                    recordingThread.IsBackground = true;
                    CreateCaptureBuffer();
                    isActive = true;
                }
            }
            catch (Exception e)
            {
                SoundControl.WriteErrorLog(e.ToString());
            }
        }
Ejemplo n.º 26
0
        public static SoundCaptureDevice[] GetDevices()
        {
            CaptureDevicesCollection  captureDevices = new CaptureDevicesCollection();
            List <SoundCaptureDevice> devices        = new List <SoundCaptureDevice>();

            foreach (DeviceInformation captureDevice in captureDevices)
            {
                devices.Add(new SoundCaptureDevice(captureDevice.DriverGuid, captureDevice.Description));
            }
            return(devices.ToArray());
        }
Ejemplo n.º 27
0
        public static SoundCaptureDevice[] GetDevices()
        {
            CaptureDevicesCollection  captureDevices = new CaptureDevicesCollection();
            List <SoundCaptureDevice> devices        = new List <SoundCaptureDevice>();

            foreach (DeviceInformation captureDevice in captureDevices)
            {
                // здесь может возникнуть ошибка если сборка была произведена на плафторму x64
                devices.Add(new SoundCaptureDevice(captureDevice.DriverGuid, captureDevice.Description));
            }
            return(devices.ToArray());
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Gets the audio input device with the given name.
        /// </summary>
        /// 
        /// <param name="name">The name of the device.</param>
        /// <returns>The named device.</returns>
        private Capture GetAudioInputDevice(string name)
        {
            if (devices == null) {
            devices = new CaptureDevicesCollection();
              }
              for (int i = 0; i < devices.Count; ++i) {
            if (devices[i].Description == name) {
              return new Capture(devices[i].DriverGuid);
            }
              }

              throw new ArgumentException("No input device with that name was found.");
        }
Ejemplo n.º 29
0
        /*
         * Initializes all the data members.
         */
        private void Initialize()
        {
            try
            {
                device = new Device();
                device.SetCooperativeLevel(this, CooperativeLevel.Normal);

                CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

                DeviceInformation deviceInfo = captureDeviceCollection[0];

                capture = new Capture(deviceInfo.DriverGuid);

                short channels         = 1;     //Stereo.
                short bitsPerSample    = 16;    //16Bit, alternatively use 8Bits.
                int   samplesPerSecond = 44100; //11KHz use 11025 , 22KHz use 22050, 44KHz use 44100 etc.

                //Set up the wave format to be captured.
                waveFormat                       = new WaveFormat();
                waveFormat.Channels              = channels;
                waveFormat.FormatTag             = WaveFormatTag.Pcm;
                waveFormat.SamplesPerSecond      = samplesPerSecond;
                waveFormat.BitsPerSample         = bitsPerSample;
                waveFormat.BlockAlign            = (short)(channels * (bitsPerSample / (short)8));
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

                captureBufferDescription             = new CaptureBufferDescription();
                captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond;//approx 200 milliseconds of PCM data.
                captureBufferDescription.Format      = waveFormat;

                playbackBufferDescription             = new BufferDescription();
                playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond;
                playbackBufferDescription.Format      = waveFormat;
                playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

                bufferSize = captureBufferDescription.BufferBytes;

                bIsCallActive  = false;
                nUdpClientFlag = 0;

                speaker      = new Speakers();
                speaker.Mono = true;
                Volume vol;
                vol = Volume.Min;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Audio device(s) missing", "VCES - Audio device error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
Ejemplo n.º 30
0
        // returns a list of input devices
        public ArrayList GetInputDevices()
        {
            // gathers the available capture devices
            CaptureDevicesCollection devices = new CaptureDevicesCollection();

            //ArrayList to collect all the availabel devices
            ArrayList m_devicesList = new ArrayList();

            foreach (DeviceInformation info in devices)
            {
                m_devicesList.Add(info.Description);
            }
            return(m_devicesList);
        }
        public SoundCardControl()
        {
            CaptureDevicesCollection captureDevicesCollection = new CaptureDevicesCollection();

            if (captureDevicesCollection.Count > 0)
            {
                this.capture_ = new Microsoft.DirectX.DirectSound.Capture(captureDevicesCollection[0].DriverGuid);
            }
            else
            {
                Console.WriteLine("No Capture Device");
            }
            this.waveFormat_  = this.CreateWaveFormat();
            this.notifyEvent_ = new AutoResetEvent(false);
        }
 public static SoundCaptureDevice GetDefaultDevice()
 {
     CaptureDevicesCollection captureDevices = new CaptureDevicesCollection();
     SoundCaptureDevice device = null;
     foreach (DeviceInformation captureDevice in captureDevices)
     {
         if(captureDevice.DriverGuid == Guid.Empty)
         {
             device = new SoundCaptureDevice(captureDevice.DriverGuid, captureDevice.Description);
             break;
         }
     }
     if (device == null)
         throw new SoundCaptureException("Default capture device is not found");
     return device;
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Create a new sound recorder.
        /// </summary>
        /// <param name="type">Sound capture device.</param>
        /// <param name="rate">Desired sample rate.</param>
        /// <param name="size">Desired sample size.</param>
        /// <param name="channels">Desired channels to use.</param>
        public SoundRecorder(SoundDeviceType type, SampleRate rate, SampleSize size, short channels)
        {
            this._desiredDeviceType = type;
            this._devices           = new CaptureDevicesCollection();

            if (this._devices == null || this._devices.Count < 1)
            {
                throw new InvalidOperationException("No sound capture devices detected.");
            }

            this.Find(type);

            InitDirectSound();

            this._recorderFormat = new SoundFormat(this._applicationDevice, rate, size, channels);
        }
Ejemplo n.º 34
0
        public SoundRecorder()
        {
            CaptureDevicesCollection devices = new CaptureDevicesCollection();

            if (devices.Count > 0)
            {
                capture_ = new Capture(devices[0].DriverGuid);
            }
            else
            {
                Console.WriteLine("No Capture Device");
            }

            waveFormat_ = CreateWaveFormat();

            notifyEvent_ = new AutoResetEvent(false);
        }
Ejemplo n.º 35
0
        private void Initialize()
        {
            try
            {
                device = new Device();
                System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(this);
                device.SetCooperativeLevel(helper.Handle, CooperativeLevel.Normal);

                CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

                DeviceInformation deviceInfo = captureDeviceCollection[0];

                capture = new Capture(deviceInfo.DriverGuid);

                short channels         = 1;     //Stereo.
                short bitsPerSample    = 16;    //16Bit, alternatively use 8Bits.
                int   samplesPerSecond = 22050; //11KHz use 11025 , 22KHz use 22050, 44KHz use 44100 etc.

                //Set up the wave format to be captured.
                waveFormat                       = new WaveFormat();
                waveFormat.Channels              = channels;
                waveFormat.FormatTag             = WaveFormatTag.Pcm;
                waveFormat.SamplesPerSecond      = samplesPerSecond;
                waveFormat.BitsPerSample         = bitsPerSample;
                waveFormat.BlockAlign            = (short)(channels * (bitsPerSample / (short)8));
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

                captureBufferDescription             = new Microsoft.DirectX.DirectSound.CaptureBufferDescription();
                captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;//approx 200 milliseconds of PCM data.
                captureBufferDescription.Format      = waveFormat;

                playbackBufferDescription             = new BufferDescription();
                playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
                playbackBufferDescription.Format      = waveFormat;
                playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

                bufferSize = captureBufferDescription.BufferBytes;

                bIsCallActive  = false;
                nUdpClientFlag = 0;
            }
            catch (Exception ex)
            {
                this.VoiceChartStart.IsEnabled = false;
            }
        }
Ejemplo n.º 36
0
 public bool CreateCaputerDevice()
 {
     // 首先要枚舉可用的捕捉設備
     CaptureDevicesCollection capturedev = new CaptureDevicesCollection();
     Guid devguid;
     if (capturedev.Count > 0)
     {
         devguid = capturedev[0].DriverGuid;  // 0 為音效卡本身之錄音
         //devguid = capturedev[2].DriverGuid;  // *********************** 這台電腦的錄音設備為 2
     }
     else
     {
         Console.WriteLine("當前沒有可用於音頻捕捉的設備", "系统提示");
         return false;
     }
     // 利用設備 GUID 來建立一個捕捉設備對象
     capture = new Capture(devguid);
     return true;
 }
Ejemplo n.º 37
0
        public static string[] EnumerateCaptureDevices()
        {
            // Get the Windows enumerated Capture devices adding a "-n" tag (-1, -2, etc.) if any duplicate names
            CaptureDevicesCollection cllCaptureDevices = new CaptureDevicesCollection();
            //DeviceInformation objDI = new DeviceInformation();
            int intCtr = 0;
            int intDupeDeviceCnt = 0;

            string[] strCaptureDevices = new string[cllCaptureDevices.Count];
            foreach (DeviceInformation objDI in cllCaptureDevices) {
            DeviceDescription objDD = new DeviceDescription(objDI);
            strCaptureDevices[intCtr] = objDD.ToString().Trim();
            intCtr += 1;
            }

            for (int i = 0; i <= strCaptureDevices.Length - 1; i++) {
            intDupeDeviceCnt = 1;
            for (int j = i + 1; j <= strCaptureDevices.Length - 1; j++) {
                if (strCaptureDevices[j] == strCaptureDevices[i]) {
                    intDupeDeviceCnt += 1;
                    strCaptureDevices[j] = strCaptureDevices[i] + "-" + intDupeDeviceCnt.ToString();
                }
            }
            }
            return strCaptureDevices;
        }
Ejemplo n.º 38
0
 /// <summary>
 /// 创建音频捕捉设备对象
 /// </summary>
 /// <returns>创建是否成功</returns>
 private bool CreateCaptureDevice()
 {
     CaptureDevicesCollection captureDevs = new CaptureDevicesCollection();
     Guid guidDev;
     if (captureDevs.Count > 0)
     {
         guidDev = captureDevs[0].DriverGuid;
     } // end of if
     else
     {
         MessageBox.Show("没有找到音频捕捉设备,请确认麦克风是否插好");
         return false;
     } // end of else
     m_objCapture = new Capture(guidDev);
     return true;
 }
Ejemplo n.º 39
0
        private bool InitCaptureDevice()
        {
            CaptureDevicesCollection devices = new CaptureDevicesCollection();
            Guid deviceGuid = Guid.Empty;
            if (devices.Count > 0)
                deviceGuid = devices[0].DriverGuid;
            else
            {
                Debug.WriteLine("No audio device in the system.");
                return false;
            }

            try
            {
                mCapDev = new Capture(deviceGuid);
            }
            catch (DirectXException e)
            {
                Debug.WriteLine(e.ToString());
                return false;
            }
            return true;
        }
Ejemplo n.º 40
0
 private void StartRecordAndSend()
 {
     try
     {
         Capture capture = null;
         CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();
         try
         {
             capture = new Capture(captureDeviceCollection[ConfSingleton.Instance.CaptureDeviceIndex].DriverGuid);
         }
         catch
         {
             capture = new Capture(captureDeviceCollection[0].DriverGuid);
         }
         captureBuffer = new CaptureBuffer(captureBufferDescription, capture);
         SetBufferEvents();
         int halfBuffer = bufferSize / 2;
         captureBuffer.Start(true);
         bool readFirstBufferPart = true;
         int offset = 0;
         MemoryStream memStream = new MemoryStream(halfBuffer);
         bStop = false;
         while (!bStop)
         {
             autoResetEvent.WaitOne();
             memStream.Seek(0, SeekOrigin.Begin);
             captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None);
             readFirstBufferPart = !readFirstBufferPart;
             offset = readFirstBufferPart ? 0 : halfBuffer;
             rtpSender.Send(ConfSingleton.Instance.Compression ? ALawEncoder.ALawEncode(memStream.GetBuffer()) : memStream.GetBuffer());
         }
     }
     catch (ThreadAbortException)
     {
         /* This is OK. It's raised when the record thread is stopped. */
     }
     /* Catch DirectSound's uninformative exceptions and attempt to expand on them... */
     catch (Exception ex)
     {
         if (OnCaptureError != null)
         {
             AudioCaptureException captureException = new AudioCaptureException("There was a problem in the audio capture process. This is often due to no working capture device being available.", ex);
             OnCaptureError(this, new AudioCaptureExceptionEventArgs() { Exception = captureException });
         }
     }
     finally
     {
         try
         {
             if (captureBuffer != null)
                 captureBuffer.Stop();
             bStop = true;
         }
         catch { }
     }
 }
Ejemplo n.º 41
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.textBox_ffmpegPath.Text = Properties.Settings.Default.ffmpegpath;
            this.textBox_inputstream.Text = Properties.Settings.Default.inputstream;
            this.textBox_audiorate.Text = Properties.Settings.Default.audiorate;
            this.textBox_videorate.Text = Properties.Settings.Default.videorate;
            this.textBox_exPort.Text = Properties.Settings.Default.port;

            if (Properties.Settings.Default.reencode_flag)
            { // 再エンコあり
                radioButton_reencode_1.Checked = true;
                groupBox_reencode.Enabled = true;
            }
            else {
                radioButton_reencode_2.Checked = true;
                groupBox_reencode.Enabled = false;
            }

            this.textBox_enc_width.Text = Properties.Settings.Default.enc_width;
            this.textBox_enc_height.Text = Properties.Settings.Default.enc_height;
            this.textBox_enc_bitrate_v.Text = Properties.Settings.Default.enc_bitrate_v;
            this.textBox_enc_bitrate_a.Text = Properties.Settings.Default.enc_bitrate_a;
            this.textBox_enc_framerate.Text = Properties.Settings.Default.enc_framerate;

            logoutputDelegate = new LogoutputDelegate(logoutput);
            this.button_disconnect.Enabled = false;
            this.textBox_log.AppendText("アプリケーションが開始しました。\r\n");

            // デバイスリストを取得してリストボックスに
            CaptureDevicesCollection myDevices = new CaptureDevicesCollection();
            foreach (DeviceInformation devInfo in myDevices)
            {

                string strDesc = devInfo.Description;
                Guid guid = devInfo.DriverGuid;
                string strModule = devInfo.ModuleName;
                this.textBox_log.AppendText(strDesc+"\r\n");
            }
        }
Ejemplo n.º 42
0
        static void InicialiceCaptureBuffer()
        {
            try
            {
                CaptureDevicesCollection audioDevices = new CaptureDevicesCollection();

                // initialize the capture buffer and start the animation thread
                Capture cap = new Capture(audioDevices[1].DriverGuid);
                CaptureBufferDescription desc = new CaptureBufferDescription();
                WaveFormat wf = new WaveFormat();
                wf.BitsPerSample = 16;
                wf.SamplesPerSecond = 44100;
                wf.Channels = (short)cap.Caps.Channels;
                wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8);
                wf.AverageBytesPerSecond = wf.BlockAlign * wf.SamplesPerSecond;
                wf.FormatTag = WaveFormatTag.Pcm;

                desc.Format = wf;
                desc.BufferBytes = SAMPLES * wf.BlockAlign;

                buffer = new CaptureBuffer(desc, cap);
                buffer.Start(true);
            }
            catch
            {
                Console.WriteLine("Error al iniciar el capturador de sonido");
            }
        }
Ejemplo n.º 43
0
        /*
         * Initializes all the data members.
         */
        private void Initialize()
        {
            try
            {
                device = new Device();
                device.SetCooperativeLevel(this, CooperativeLevel.Normal);

                CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

                DeviceInformation deviceInfo = captureDeviceCollection[0];

                capture = new Capture(deviceInfo.DriverGuid);

                short channels = 1; //Stereo.
                short bitsPerSample = 16; //16Bit, alternatively use 8Bits.
                int samplesPerSecond = 22050; //11KHz use 11025 , 22KHz use 22050, 44KHz use 44100 etc.

                //Set up the wave format to be captured.
                waveFormat = new WaveFormat();
                waveFormat.Channels = channels;
                waveFormat.FormatTag = WaveFormatTag.Pcm;
                waveFormat.SamplesPerSecond = samplesPerSecond;
                waveFormat.BitsPerSample = bitsPerSample;
                waveFormat.BlockAlign = (short)(channels * (bitsPerSample / (short)8));
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

                captureBufferDescription = new CaptureBufferDescription();
                captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;//approx 200 milliseconds of PCM data.
                captureBufferDescription.Format = waveFormat;

                playbackBufferDescription = new BufferDescription();
                playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
                playbackBufferDescription.Format = waveFormat;
                playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

                bufferSize = captureBufferDescription.BufferBytes;

                bIsCallActive = false;
                nUdpClientFlag = 0;

                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450);
                //Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc).
                clientSocket.Bind(ourEP);

                //Receive data from any IP.
                EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));

                byteData = new byte[1024];
                //Receive data asynchornously.
                clientSocket.BeginReceiveFrom(byteData,
                                           0, byteData.Length,
                                           SocketFlags.None,
                                           ref remoteEP,
                                           new AsyncCallback(OnReceive),
                                           null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "VoiceChat-Initialize ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Gets the audio input device with the given name.
        /// </summary>
        /// 
        /// <param name="name">The name of the device.</param>
        /// <returns>The named device.</returns>
        private Capture GetAudioInputDevice(string name)
        {
            if (devices == null) {
            devices = new CaptureDevicesCollection();
              }
              //For Default
              if (name.Equals("") || name == null)
              {
            return new Capture(devices[0].DriverGuid);
              }
              //For Specified
              for (int i = 0; i < devices.Count; ++i) {
            if (devices[i].Description == name) {
              return new Capture(devices[i].DriverGuid);
            }
              }

              throw new ArgumentException("No input device with that name was found.");
        }
Ejemplo n.º 45
0
        public void Initialize()
        {
            try
            {
                LogLine("Getting local IP address...");
                LocalIP.Text = NetProcedures.GetLocalIPAddress();
                LogLine("Using global IP address...");
                GlobalIP.Text = NetProcedures.globalIP;

                LogLine("Connecting to capturing device...");
                device = new Device();
                device.SetCooperativeLevel(this, CooperativeLevel.Normal);

                CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

                DeviceInformation deviceInfo = captureDeviceCollection[0];

                capture = new Capture(deviceInfo.DriverGuid);

                LogLine("Preparing audio format to be captured...");

                short channels = (short)Channels.Value;
                short bitsPerSample;
                if (radioButton7.Checked) bitsPerSample = 8;
                else bitsPerSample = 16;
                int samplesPerSecond;
                if (radioButton1.Checked) samplesPerSecond = 11025;
                else if (radioButton2.Checked) samplesPerSecond = 22050;
                else samplesPerSecond = 44100;

                //Set up the wave format to be captured.
                waveFormat = new WaveFormat();
                waveFormat.Channels = channels;
                waveFormat.FormatTag = WaveFormatTag.Pcm;
                waveFormat.SamplesPerSecond = samplesPerSecond;
                waveFormat.BitsPerSample = bitsPerSample;
                waveFormat.BlockAlign = (short)(channels * (bitsPerSample / (short)8));
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

                captureBufferDescription = new CaptureBufferDescription();
                captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;//approx 200 milliseconds of PCM data.
                captureBufferDescription.Format = waveFormat;

                playbackBufferDescription = new BufferDescription();
                playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
                playbackBufferDescription.Format = waveFormat;
                playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

                bufferSize = captureBufferDescription.BufferBytes;

                bIsCallActive = false;
                nUdpClientFlag = 0;

                //Using UDP sockets
                LogLine("Initializing a socket...");
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                
                EndPoint ourEP = new IPEndPoint(IPAddress.Any, 3535);
                clientSocket.Bind(ourEP);

                //Receive data from any IP.
                EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));

                byteData = new byte[1024];
                //Receive data asynchornously.
                LogLine("Preparing to receive data...");
                clientSocket.BeginReceiveFrom(byteData,
                                           0, byteData.Length,
                                           SocketFlags.None,
                                           ref remoteEP,
                                           new AsyncCallback(OnReceive),
                                           null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка инициализации | Fenazy", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// 创建录音服务对象
        /// </summary>
        /// <param name="owner">宿主</param>
        /// <param name="deviceIndex">设备序号(0 - 默认设备)</param>
        /// <param name="channelCount">通道数</param>
        /// <param name="frequency">采样频率(次/秒)</param>
        /// <param name="sampleSize">样本尺寸(位/次)</param>
        /// <param name="bufferSectionTimeSpan">缓冲区片段的时间间隔</param>
        /// <param name="bufferSectionCount">缓冲区片段数</param>
        /// <param name="notificationEvent">通知点信号(工作线程等待此信号)</param>
        public SoundRecorder(Control owner, int deviceIndex, short channelCount, int frequency, short sampleSize, TimeSpan bufferSectionTimeSpan, int bufferSectionCount, AutoResetEvent notificationEvent)
            : base()
        {
            //宿主
            this.Owner = owner;

            #region 设备

            CaptureDevicesCollection devices = new CaptureDevicesCollection();
            this.Device = new Capture(devices[deviceIndex].DriverGuid);

            #endregion

            #region 缓冲区描述

            #region Wave格式

            WaveFormat format = new WaveFormat();
            format.FormatTag = WaveFormatTag.Pcm;                                       //格式类型
            format.Channels = channelCount;                                             //通道数
            format.SamplesPerSecond = frequency;                                        //采样频率(次/秒)
            format.BitsPerSample = sampleSize;                                          //样本尺寸(位/次)
            format.BlockAlign = (short)((format.BitsPerSample / 8) * format.Channels);  //数据块的最小单元(字节/次)
            format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond; //采样性能(字节/秒)

            #endregion

            //缓冲区片段尺寸
            int bufferSectionSize = format.AverageBytesPerSecond * (int)bufferSectionTimeSpan.TotalSeconds;
            //缓冲区尺寸
            int bufferSize = bufferSectionSize * bufferSectionCount;

            //创建
            CaptureBufferDescription bufferDescription = new CaptureBufferDescription();
            bufferDescription.Format = format;
            bufferDescription.BufferBytes = bufferSize;
            this.BufferDescription = bufferDescription;

            #endregion

            #region 缓冲区位置通知序列

            //通知点信号
            this.NotificationEvent = notificationEvent;
            //位置通知序列
            this.BufferPositionNotifys = new BufferPositionNotify[bufferSectionCount];
            for (int i = 0; i < bufferSectionCount; i++)
            {
                this.BufferPositionNotifys[i].Offset = bufferSectionSize * (i + 1) - 1; //通知点
                this.BufferPositionNotifys[i].EventNotifyHandle = this.NotificationEvent.SafeWaitHandle.DangerousGetHandle(); //通知点信号 Set()
            }

            #endregion

            #region 工作线程

            this.ThreadWorking = true;
            this.WorkingThread = new Thread(new ParameterizedThreadStart(this.WorkingThreadProcess));
            this.WorkingThread.IsBackground = true;
            this.WorkingThread.Start(this.NotificationEvent); //带入参数

            #endregion
        }
Ejemplo n.º 47
0
 private bool CreateCaptuerDevice()
 {
     //首先要玫举可用的捕捉设备
     CaptureDevicesCollection capturedev = new CaptureDevicesCollection();
     Guid devguid;
     if (capturedev.Count > 0)
     {
         devguid = capturedev[0].DriverGuid;
     }
     else
     {
         MessageBox.Show("当前没有可用于音频捕捉的设备", "系统提示");
         return false;
     }
     //利用设备GUID来建立一个捕捉设备对象
     capture = new Capture(devguid);
     return true;
 }
Ejemplo n.º 48
0
Archivo: Main.cs Proyecto: ptaa32/ARDOP
        public bool StartCodec(ref string strFault)
        {
            bool functionReturnValue = false;
            //Returns true if successful
            Thread.Sleep(100);
            // This delay is necessary for reliable starup following a StopCodec
            lock (objCodecLock) {
            dttLastSoundCardSample = Now;
            bool blnSpectrumSave = MCB.DisplaySpectrum;
            bool blnWaterfallSave = MCB.DisplayWaterfall;
            System.DateTime dttStartWait = Now;
            MCB.DisplayWaterfall = false;
            MCB.DisplaySpectrum = false;
            string[] strCaptureDevices = EnumerateCaptureDevices();
            string[] strPlaybackDevices = EnumeratePlaybackDevices();
            functionReturnValue = false;
            DeviceInformation objDI = new DeviceInformation();
            int intPtr = 0;
            // Playback devices
            try {
                cllPlaybackDevices = null;

                cllPlaybackDevices = new Microsoft.DirectX.DirectSound.DevicesCollection();
                if ((devSelectedPlaybackDevice != null)) {
                    devSelectedPlaybackDevice.Dispose();
                    devSelectedPlaybackDevice = null;
                }

                foreach (DeviceInformation objDI in cllPlaybackDevices) {
                    DeviceDescription objDD = new DeviceDescription(objDI);
                    if (strPlaybackDevices(intPtr) == MCB.PlaybackDevice) {
                        if (MCB.DebugLog)
                            Logs.WriteDebug("[Main.StartCodec] Setting SelectedPlaybackDevice = " + MCB.PlaybackDevice);
                        devSelectedPlaybackDevice = new Device(objDD.info.DriverGuid);
                        functionReturnValue = true;
                        break; // TODO: might not be correct. Was : Exit For
                    }
                    intPtr += 1;
                }
                if (!functionReturnValue) {
                    strFault = "Playback Device setup, Device " + MCB.PlaybackDevice + " not found in Windows enumerated Playback Devices";
                }
            } catch (Exception ex) {
                strFault = Err.Number.ToString + "/" + Err.Description;
                Logs.Exception("[StartCodec], Playback Device setup] Err: " + ex.ToString);
                functionReturnValue = false;
            }
            if (functionReturnValue) {
                // Capture Device
                CaptureBufferDescription dscheckboxd = new CaptureBufferDescription();
                try {
                    functionReturnValue = false;
                    cllCaptureDevices = null;
                    cllCaptureDevices = new CaptureDevicesCollection();
                    intPtr = 0;
                    for (int i = 0; i <= cllCaptureDevices.Count - 1; i++) {
                        if (MCB.CaptureDevice == strCaptureDevices(i)) {
                            objCaptureDeviceGuid = cllCaptureDevices(i).DriverGuid;
                            devCaptureDevice = new Capture(objCaptureDeviceGuid);
                            stcSCFormat.SamplesPerSecond = 12000;
                            // 12000 Hz sample rate
                            stcSCFormat.Channels = 1;
                            stcSCFormat.BitsPerSample = 16;
                            stcSCFormat.BlockAlign = 2;
                            stcSCFormat.AverageBytesPerSecond = 2 * 12000;
                            stcSCFormat.FormatTag = WaveFormatTag.Pcm;
                            objApplicationNotify = null;
                            objCapture = null;
                            // Set the buffer sizes
                            intCaptureBufferSize = intNotifySize * intNumberRecordNotifications;
                            // Create the capture buffer
                            dscheckboxd.BufferBytes = intCaptureBufferSize;
                            stcSCFormat.FormatTag = WaveFormatTag.Pcm;
                            dscheckboxd.Format = stcSCFormat;
                            // Set the format during creatation
                            if ((objCapture != null)) {
                                objCapture.Dispose();
                                objCapture = null;
                            }
                            //objCapture = New CaptureBuffer(dscheckboxd, devCaptureDevice)
                            intNextCaptureOffset = 0;
                            WriteTextToSpectrum("CODEC Start OK", Brushes.LightGreen);
                            while (Now.Subtract(dttStartWait).TotalSeconds < 3) {
                                Application.DoEvents();
                                Thread.Sleep(100);
                            }
                            objCapture = new CaptureBuffer(dscheckboxd, devCaptureDevice);
                            InititializeNotifications();
                            objCapture.Start(true);
                            // start with looping
                            InititializeSpectrum(Color.Black);

                            functionReturnValue = true;
                        }
                    }
                    if (!functionReturnValue) {
                        strFault = "Could not find DirectSound capture device " + MCB.CaptureDevice.ToUpper;
                        //Logs.Exception("[Main.StartCodec] Could not find DirectSound capture device " & MCB.CaptureDevice & " in Windows enumerated Capture Devices")
                    }
                } catch (Exception ex) {
                    strFault = Err.Number.ToString + "/" + Err.Description;
                    functionReturnValue = false;
                    //Logs.Exception("[Main.StartCodec] Err: " & ex.ToString)
                }
            }

            if (functionReturnValue) {
                if (MCB.DebugLog)
                    Logs.WriteDebug("[Main.StartCodec] Successful start of codec");
                objProtocol.ARDOPProtocolState = ProtocolState.DISC;
            } else {
                if (MCB.DebugLog)
                    Logs.WriteDebug("[Main.StartCodec] CODEC Start Failed");
                WriteTextToSpectrum("CODEC Start Failed", Brushes.Red);
                objProtocol.ARDOPProtocolState = ProtocolState.OFFLINE;
                while (Now.Subtract(dttStartWait).TotalSeconds < 3) {
                    Application.DoEvents();
                    Thread.Sleep(100);
                }
                tmrStartCODEC.Interval = 5000;
                tmrStartCODEC.Start();
            }
            InititializeSpectrum(Color.Black);
            MCB.DisplayWaterfall = blnWaterfallSave;
            MCB.DisplaySpectrum = blnSpectrumSave;
            }
            return functionReturnValue;
        }
Ejemplo n.º 49
0
        void FillCombos()
        {
            //Record Devices
            CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();
            cmbRecordDevices.ValueMember = "DriverGuid";
            cmbRecordDevices.DisplayMember = "Description";
            foreach (DeviceInformation item in captureDeviceCollection)
            {
                _devices.Add(new capture_device()
                {
                     Description = item.Description, ModuleName = item.ModuleName,
                     DriverGuid = item.DriverGuid
                });
            }
            cmbRecordDevices.DataSource = _devices;

            cmbBitsPerSample.DisplayMember = cmbSoundChannels.DisplayMember = cmbSoundSamplesxsec.DisplayMember = "description";
            cmbBitsPerSample.ValueMember = cmbSoundChannels.ValueMember = cmbSoundSamplesxsec.ValueMember = "value";

            //BitsXSample
            _combo_channels.Add(new combo_properties() { description = "Mono", value = 0 });
            _combo_channels.Add(new combo_properties() { description = "Estereo", value = 1 });
            cmbSoundChannels.DataSource = _combo_channels;

            //Channels
            _combo_bits_sample.Add(new combo_properties() { description = "8Bit", value = 8 });
            _combo_bits_sample.Add(new combo_properties() { description = "16Bit", value = 16 });
            cmbBitsPerSample.DataSource = _combo_bits_sample;

            //Samplesxsec
            _combo_samples_second.Add(new combo_properties() { description = "11KHz", value = 11025 });
            _combo_samples_second.Add(new combo_properties() { description = "22KHz", value = 22050 });
            _combo_samples_second.Add(new combo_properties() { description = "44KHz", value = 44100 });
            cmbSoundSamplesxsec.DataSource = _combo_samples_second;

               cmbBitsPerSample.SelectedIndex = cmbSoundChannels.SelectedIndex = cmbSoundSamplesxsec.SelectedIndex = 1;
               cmbCodecs.SelectedIndex = 0;
               cmbRecordDevices.SelectedIndex = 0;
            //short channels = 1; //Stereo.
            //short bitsPerSample = 16; //16Bit, alternatively use 8Bits.
            //int samplesPerSecond = 22050; //11KHz use 11025 , 22KHz use 22050, 44KHz use 44100 etc.
        }
Ejemplo n.º 50
0
 /// <summary>
 /// 初始化录音设备,此处使用主录音设备
 /// </summary>
 /// <returns>调用成功返回true,否则false</returns>
 bool InitCaptureDevice()
 {
     //获取默认的音频捕捉设备
     CaptureDevicesCollection devices = new CaptureDevicesCollection();
     Guid deviceGuid = Guid.Empty;
     if (devices.Count > 0)
         deviceGuid = devices[0].DriverGuid;
     else
     {
         MessageBox.Show("系统中没有音频捕捉设备");
         return false;
     }
     // 用指定的捕捉设备创建Capture对象
     try
     {
         mCapDev = new Capture(deviceGuid);
     }
     catch (DirectXException e)
     {
         MessageBox.Show(e.ToString());
         return false;
     }
     return true;
 }