Exemplo n.º 1
0
    public void StartCapturing()
    {
        try
        {
            _captureBuffer = new CaptureBuffer(_capBufDescr, _capture);
            SetBufferEvents();
            int halfBuffer = _bufferSize / 2;
            _captureBuffer.Start(true);
            bool         readFirstBufferPart = true;
            int          offset    = 0;
            MemoryStream memStream = new MemoryStream(halfBuffer);

            while (true)
            {
                _eventToReset.WaitOne();

                memStream.Seek(0, SeekOrigin.Begin);
                _captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None);
                readFirstBufferPart = !readFirstBufferPart;
                offset = readFirstBufferPart ? 0 : halfBuffer;

                byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer());

                if (!_StopLoop)
                {
                    OnBufferFulfill(dataToWrite, null);
                }
            }
        }
        catch {}
    }
Exemplo n.º 2
0
        void WaveInDataAvailable(object sender, WaveInEventArgs e)
        {
            //forces processing of volume level without piping it out
            var sampleBuffer = new float[e.BytesRecorded];

            if (_meteringProvider != null)
            {
                _meteringProvider.Read(sampleBuffer, 0, e.BytesRecorded);

                if (OutSockets.Count > 0)
                {
                    var enc = new byte[e.Buffer.Length / 2];
                    ALawEncoder.ALawEncode(e.Buffer, enc);

                    for (int i = 0; i < OutSockets.Count; i++)
                    {
                        Socket s = OutSockets[i];
                        if (s.Connected)
                        {
                            if (!SendToBrowser(enc, s))
                            {
                                OutSockets.Remove(s);
                                i--;
                            }
                        }
                        else
                        {
                            OutSockets.Remove(s);
                            i--;
                        }
                    }
                }
            }
        }
    public void StartCapturing()
    {
        try
        {
            captureBuffer = new CaptureBuffer(captureBufferDescription, capture); // Set Buffer Size,Voice Recording Format & Input Voice Device
            SetBufferEvents();                                                    // Set the events Positions to Send While Recording
            int halfBuffer = bufferSize / 2;                                      // Take the half buffer size
            captureBuffer.Start(true);                                            // start capturing
            bool         readFirstBufferPart = true;                              // to know which part has been filled (the buufer has been divided into tow parts)
            int          offset    = 0;                                           // at point 0
            MemoryStream memStream = new MemoryStream(halfBuffer);                // set the half buffer size to the memory stream

            while (true)                                                          // Looping until Stoploop=true Set by the talker
            {
                //WaitOne() Blocks the current thread until the current WaitHandle receives a signal
                //WaitHandle("Encapsulates operating system–specific objects that wait for exclusive access to shared resources")
                autoResetEvent.WaitOne();

                memStream.Seek(0, SeekOrigin.Begin);                                //Sets the position within the current stream to 0
                captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None);   // capturing and set to MemoryStream
                readFirstBufferPart = !readFirstBufferPart;                         // reflecting the boolean value to set the new comming buffer to the other part
                offset = readFirstBufferPart ? 0 : halfBuffer;                      // if readFirstBufferPart set to true then set the offset to 0 else set the offset to the half buffer

                byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer()); // G.711 Encoding, Compress to less then 50%

                if (!StopLoop)
                {
                    OnBufferFulfill(dataToWrite, null);
                }
            }
        }
        catch {}
    }
Exemplo n.º 4
0
        // Encode G.711
        private void button2_Click(object sender, EventArgs e)
        {
            try {
                if (this.currentAudio == null)
                {
                    throw new Exception("Вы не выбрали файл для кодирования.");
                }
                if (codecToEncode.SelectedItem == null)
                {
                    throw new Exception("Вы не выбрали кодэк.");
                }
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            SaveFileDialog save = new SaveFileDialog();

            save.Filter = "Wave File (*.wav)|*.wav;";
            if (save.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            Codecs codec = (codecToEncode.SelectedIndex == 0) ? Codecs.ALAW : Codecs.MULAW;

            byte[] samples = new byte[this.currentAudio.ShortSamples.Length];
            for (int i = 0; i < this.currentAudio.ShortSamples.Length; i++)
            {
                if (codec == Codecs.ALAW)
                {
                    samples[i] = ALawEncoder.LinearToALawSample(this.currentAudio.ShortSamples[i]);
                }
                else if (codec == Codecs.MULAW)
                {
                    samples[i] = MuLawEncoder.LinearToMuLawSample(this.currentAudio.ShortSamples[i]);
                }
            }
            WaveFormat format = null;

            if (codec == Codecs.ALAW)
            {
                format = WaveFormat.CreateALawFormat(this.currentAudio.SampleRate, this.currentAudio.Stream.WaveFormat.Channels);
            }
            else if (codec == Codecs.MULAW)
            {
                format = WaveFormat.CreateMuLawFormat(this.currentAudio.SampleRate, this.currentAudio.Stream.WaveFormat.Channels);
            }
            WaveFileWriter writer = new WaveFileWriter(save.FileName, format);

            writer.Write(samples, 0, samples.Length);
            writer.Close();
            DialogResult dres = MessageBox.Show("Аудиофайл успешно сохранен. Открыть файл?", "Файл сохранен", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dres == DialogResult.Yes)
            {
                this.decodeG711(save.FileName, codec);
            }
        }
Exemplo n.º 5
0
        /*
         * Send synchronously sends data captured from microphone across the network on port 1550.
         */
        private void UDP_Send()
        {
            try {
                //The following lines get audio from microphone and then send them
                //across network.

                captureBuffer = new CaptureBuffer(captureBufferDescription, capture);

                UDP_CreateNotifyPositions();

                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;

                    //TODO: Fix this ugly way of initializing differently.

                    //Choose the vocoder. And then send the data to other party at port 1550.


                    byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer());
                    udpClient.Send(dataToWrite, dataToWrite.Length, otherPartyIP.Address.ToString(), 6068);
                }
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "VoiceChat-Send ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } finally {
                captureBuffer.Stop();

                //Increment flag by one.
                nUdpClientFlag += 1;

                //When flag is two then it means we have got out of loops in Send and Receive.
                while (nUdpClientFlag != 2)
                {
                }

                //Clear the flag.
                nUdpClientFlag = 0;

                //Close the socket.
                udpClient.Close();
            }
        }
Exemplo n.º 6
0
        public byte[] Encode(byte[] data, int offset, int length)
        {
            var encoded  = new byte[length / 2];
            var outIndex = 0;

            for (var i = 0; i < length; i += 2)
            {
                encoded[outIndex++] = ALawEncoder.LinearToALawSample(BitConverter.ToInt16(data, offset + i));
            }
            return(encoded);
        }
Exemplo n.º 7
0
 private static byte[] ALawCompress(float[] input)
 {
     byte[] array = VoiceChatBytePool.Instance.Get();
     for (int i = 0; i < input.Length; i++)
     {
         int   num    = (int)(input[i] * 32767f);
         short sample = ((num >= -32768) ? ((num <= 32767) ? ((short)num) : short.MaxValue) : short.MinValue);
         array[i] = ALawEncoder.LinearToALawSample(sample);
     }
     return(array);
 }
Exemplo n.º 8
0
        public byte[] Encode(byte[] data, int offset, int length)
        {
            byte[] encoded  = new byte[length / 2];
            int    outIndex = 0;

            for (int n = 0; n < length; n += 2)
            {
                encoded[outIndex++] = ALawEncoder.LinearToALawSample(BitConverter.ToInt16(data, offset + n));
            }
            return(encoded);
        }
Exemplo n.º 9
0
        private void AudioSourceDataAvailable(object sender, DataAvailableEventArgs e)
        {
            try
            {
                lock (_obj)
                {
                    if (_bTalking && _avstream != null)
                    {
                        byte[] bSrc     = e.RawData;
                        int    totBytes = bSrc.Length;

                        if (!_audioSource.RecordingFormat.Equals(_waveFormat))
                        {
                            using (var ws = new TalkHelperStream(bSrc, totBytes, _audioSource.RecordingFormat))
                            {
                                int j    = -1;
                                var bDst = new byte[44100];
                                totBytes = 0;
                                using (var helpStm = new WaveFormatConversionStream(_waveFormat, ws))
                                {
                                    while (j != 0)
                                    {
                                        j         = helpStm.Read(bDst, totBytes, 10000);
                                        totBytes += j;
                                    }
                                    helpStm.Close();
                                }
                                ws.Close();
                                bSrc = bDst;
                            }
                        }
                        var enc = new byte[totBytes / 2];
                        ALawEncoder.ALawEncode(bSrc, totBytes, enc);

                        try {
                            _avstream.Write(enc, 0, enc.Length);
                            _avstream.Flush();
                        }
                        catch (SocketException)
                        {
                            StopTalk();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
                StopTalk();
            }
        }
Exemplo n.º 10
0
        private void AudioSourceDataAvailable(object sender, DataAvailableEventArgs e)
        {
            try
            {
                lock (_obj)
                {
                    if (_bTalking && _avstream != null)
                    {
                        byte[] bSrc     = e.RawData;
                        int    totBytes = bSrc.Length;

                        if (!_audioSource.RecordingFormat.Equals(_waveFormat))
                        {
                            var ws      = new TalkHelperStream(bSrc, totBytes, _audioSource.RecordingFormat);
                            var helpStm = new WaveFormatConversionStream(_waveFormat, ws);
                            totBytes = helpStm.Read(bSrc, 0, 25000);
                            ws.Close();
                            ws.Dispose();
                            helpStm.Close();
                            helpStm.Dispose();
                        }
                        var enc = new byte[totBytes / 2];
                        ALawEncoder.ALawEncode(bSrc, totBytes, enc);

                        try {
                            _avstream.Write(enc, 0, enc.Length);
                            _avstream.Flush();
                        }
                        catch (SocketException)
                        {
                            StopTalk();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("", ex);//MainForm.LogExceptionToFile(ex);
                StopTalk();
            }
        }
Exemplo n.º 11
0
        private void SendAudio()
        {
            try
            {
                // Capturamos el audio y lo enviamos por la red
                int halfbuffer = buffersize / 2;
                captureBuffer = new CaptureBuffer(captureBuffDesc, capture);
                CreateNotifyPositions();
                captureBuffer.Start(true);
                bool         readFirstBufferPart = true;
                int          offset    = 0;
                MemoryStream memStream = new MemoryStream(halfbuffer);

                while (!button7.Enabled)
                {
                    // Esperamos un evento
                    autoResetEvent.WaitOne();
                    // Ponemos el puntero al principio del MS
                    memStream.Seek(0, SeekOrigin.Begin);
                    // Leemos el Buffer de Captura y lo guardamos en la primera mitad
                    captureBuffer.Read(offset, memStream, halfbuffer, LockFlag.None);
                    readFirstBufferPart = !readFirstBufferPart;
                    offset = readFirstBufferPart ? 0 : halfbuffer;

                    // Preparamos el stream de datos
                    //byte[] data = memStream.GetBuffer();    // Sin compresión
                    byte[] data = ALawEncoder.ALawEncode(memStream.GetBuffer());

                    // Enviamos via RTP al usuario.
                    audio.sendALaw(data);
                    num_audio++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error sending audio.");
            }
        }
Exemplo n.º 12
0
        void WaveInDataAvailable(object sender, WaveInEventArgs e)
        {
            //forces processing of volume level without piping it out
            var sampleBuffer = new float[e.BytesRecorded];

            if (_meteringProvider != null)
            {
                _meteringProvider.Read(sampleBuffer, 0, e.BytesRecorded);

                if (OutSockets.Count > 0)
                {
                    var enc = new byte[e.Buffer.Length / 2];
                    if (MainForm.ifF2PressProsessing)
                    {
                        ALawEncoder.ALawEncode(e.Buffer, enc);
                    }

                    for (int i = 0; i < OutSockets.Count; i++)
                    {
                        Socket s = OutSockets[i];
                        if (s.Connected)
                        {
                            //sendTextToForm(string.Format("Conneted! {0}\r\n",s.AddressFamily));
                            if (!SendToBrowser(enc, s))
                            {
                                OutSockets.Remove(s);
                                i--;
                            }
                        }
                        else
                        {
                            OutSockets.Remove(s);
                            i--;
                        }
                    }
                }
            }
        }
Exemplo n.º 13
0
        public void WaveInDataAvailable(object sender, WaveInEventArgs e)
        {
            var sampleBuffer = new float[e.BytesRecorded];

            if (_meteringProvider != null)
            {
                _meteringProvider.Read(sampleBuffer, 0, e.BytesRecorded);

                var enc = new byte[e.Buffer.Length / 2];
                //可以控制是否对语音进行编码,编码之后Client才可以播放出声音
                if (FrmVoiceSpeaker.ifF2PressProsessing)
                {
                    ALawEncoder.ALawEncode(e.Buffer, enc);
                }
                try
                {
                    SendVarData(client, enc);
                }
                catch (SocketException se)
                {
                    logger.Error("发送语音流出现异常。Exception:{0}", se.Message);
                }
            }
        }
Exemplo n.º 14
0
        private void AudioSourceDataAvailable(object sender, DataAvailableEventArgs e)
        {
            try
            {
                lock (_obj)
                {
                    if (_bTalking && _avstream != null)
                    {
                        byte[] bSrc     = e.RawData;
                        int    totBytes = bSrc.Length;
                        int    j        = -1;
                        if (!_audioSource.RecordingFormat.Equals(_waveFormat))
                        {
                            var ws = new TalkHelperStream(bSrc, totBytes, _audioSource.RecordingFormat);

                            var bDst = new byte[44100];
                            totBytes = 0;
                            using (var helpStm = new WaveFormatConversionStream(_waveFormat, ws))
                            {
                                while (j != 0)
                                {
                                    j         = helpStm.Read(bDst, totBytes, 10000);
                                    totBytes += j;
                                }
                            }
                            bSrc = bDst;
                        }
                        var enc = _muLawCodec.Encode(bSrc, 0, totBytes);
                        ALawEncoder.ALawEncode(bSrc, totBytes, enc);


                        Buffer.BlockCopy(enc, 0, _talkBuffer, _talkDatalen, enc.Length);
                        _talkDatalen += enc.Length;


                        j = 0;
                        try
                        {
                            while (j + 240 < _talkDatalen)
                            {
                                //need to write out in 240 byte packets
                                var pkt = new byte[240];
                                Buffer.BlockCopy(_talkBuffer, j, pkt, 0, 240);

                                // _avstream.Write(_hdr, 0, _hdr.Length);
                                _avstream.Write(pkt, 0, 240);
                                j += 240;
                            }
                            if (j < _talkDatalen)
                            {
                                Buffer.BlockCopy(_talkBuffer, j, _talkBuffer, 0, _talkDatalen - j);
                                _talkDatalen = _talkDatalen - j;
                            }
                        }
                        catch (SocketException)
                        {
                            StopTalk();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogExceptionToFile(ex, "TalkAxis");
                StopTalk();
            }
        }
Exemplo n.º 15
0
        // 음성정보를 전달한다.
        private void SendVoiceInfo()
        {
            try
            {
                captureBuffer = new CaptureBuffer(captureBufferDescription, capture);

                CreateNotifyPositions();

                int halfBuffer = bufferSize / 2;
                captureBuffer.Start(true);

                bool readFirstBufferPart = true;
                int  offset = 0;

                MemoryStream memStream = new MemoryStream(halfBuffer);
                bStop = false;

                VoiceInfo voiceInfo = new VoiceInfo();

                while (!bStop)
                {
                    autoResetEvent.WaitOne();
                    memStream.Seek(0, SeekOrigin.Begin);
                    captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None);
                    readFirstBufferPart = !readFirstBufferPart;
                    offset = readFirstBufferPart ? 0 : halfBuffer;

                    if (vocoder == Vocoder.ALaw)
                    {
                        byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer());

                        voiceInfo.UserId = Main_Pan._UserInfo.Id;
                        voiceInfo.Data   = dataToWrite;

                        Main_Pan._ClientEngine.Send(NotifyType.Request_VoiceChat, voiceInfo);
                    }
                    else if (vocoder == Vocoder.uLaw)
                    {
                        byte[] dataToWrite = MuLawEncoder.MuLawEncode(memStream.GetBuffer());

                        voiceInfo.UserId = Main_Pan._UserInfo.Id;
                        voiceInfo.Data   = dataToWrite;

                        Main_Pan._ClientEngine.Send(NotifyType.Request_VoiceChat, voiceInfo);
                    }
                    else
                    {
                        byte[] dataToWrite = memStream.GetBuffer();

                        voiceInfo.UserId = Main_Pan._UserInfo.Id;
                        voiceInfo.Data   = dataToWrite;

                        Main_Pan._ClientEngine.Send(NotifyType.Request_VoiceChat, voiceInfo);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                captureBuffer.Stop();
                nUdpClientFlag = 0;
            }
        }
 byte EncodeALaw( short _sample )
 {
     return ALawEncoder.LinearToALawSample(_sample);
 }
Exemplo n.º 17
0
        private void Send()
        {
            try
            {
                //The following lines captures the speech from the  microphone and then send it on to the network.

                captureBuffer = new CaptureBuffer(captureBufferDescription, capture);

                CreateNotifyPositions();

                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;
                    // Voice compression takes place here
                    if (vocoder == Vocoder.ALaw)
                    {
                        byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer());
                        udpClient.Send(dataToWrite, dataToWrite.Length, otherPartyIP.Address.ToString(), 1550);
                        // we can use either rtp or udp to send the data.
                    }

                    else
                    {
                        byte[] dataToWrite = memStream.GetBuffer();
                        udpClient.Send(dataToWrite, dataToWrite.Length, otherPartyIP.Address.ToString(), 1550);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "VoiceChat-Send ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                captureBuffer.Stop();

                //Increment flag by one.
                nUdpClientFlag += 1;

                //When flag is two then it means we have got out of loops in Send and Receive.
                while (nUdpClientFlag != 2)
                {
                }

                nUdpClientFlag = 0;
                udpClient.Close();
            }
        }
Exemplo n.º 18
0
        /*
         * Send synchronously sends data captured from microphone across the network on port 1550.
         */
        private void Send()
        {
            try
            {
                captureBuffer = new CaptureBuffer(captureBufferDescription, capture);
                //The following lines get audio from microphone and then send them
                //across network

                CreateNotifyPositions();

                int halfBuffer = bufferSize / 2;

                captureBuffer.Start(true);

                bool readFirstBufferPart = true;
                int  offset = 0;

                MemoryStream memStream = new MemoryStream(halfBuffer);
                bStop = false;
                while (!bStop)
                {
                    if (!IsMuted)
                    {
                        autoResetEvent.WaitOne();
                        memStream.Seek(0, SeekOrigin.Begin);
                        captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None);
                        readFirstBufferPart = !readFirstBufferPart;
                        offset = readFirstBufferPart ? 0 : halfBuffer;

                        //Encode and encrypt data.
                        byte[] dataEncoded = ALawEncoder.ALawEncode(memStream.GetBuffer());

                        byte[] dataToWrite = AES_Crypto.Encrypt(dataEncoded, CallCurrentPass, CallCurrentSalt);

                        udpClient.Send(dataToWrite, dataToWrite.Length, otherPartyIP.Address.ToString(), 1550);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "VoiceChat-Send ()", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            finally
            {
                captureBuffer.Stop();
                captureBuffer.Dispose();
                //Increment flag by one.
                nUdpClientFlag += 1;

                //When flag is two then it means we have got out of loops in Send and Receive.
                while (nUdpClientFlag != 2)
                {
                }

                //Clear the flag.
                nUdpClientFlag = 0;

                //Close the socket.
                udpClient.Close();
            }
        }
Exemplo n.º 19
0
        /*
         * Send synchronously sends data captured from microphone across the network on port 1550.
         */
        public void Send()
        {
            //TODO: Send Microphone Data
            //Esperamos hasta que recivamos el start del server

            try
            {
                //The following lines get audio from microphone and then send them
                //across network.

                int users_count = 0;

                //captureBuffer = new CaptureBuffer(captureBufferDescription, capture);
                //CreateNotifyPositions();
                //int halfBuffer = bufferSize / 2;
                //captureBuffer.Start(true);
                //bool readFirstBufferPart = true;
                //int offset = 0;
                //MemoryStream memStream = new MemoryStream(halfBuffer);
                //bStop = false;

                cGlobalVars.AddLogChat("Sending Started");

                lock (_music_data)
                {
                    _music_data.Clear();
                }

                while (!bStop)
                {
                    lock (clientIPs)
                    {
                        if (eMode == Mode.Server)
                        {
                            users_count = clientIPs.Count;
                        }
                        else if (eMode == Mode.Client)
                        {
                            users_count = 1;
                        }

                        if (users_count > 0)
                        {
                            //autoResetEvent.WaitOne();
                            //memStream.Seek(0, SeekOrigin.Begin);
                            ////captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None);
                            //readFirstBufferPart = !readFirstBufferPart;
                            //offset = readFirstBufferPart ? 0 : halfBuffer;

                            ////TODO: Fix this ugly way of initializing differently.
                            ////Choose the vocoder. And then send the data to other party at port 1550.
                            ////if (vocoder == Vocoder.ALaw)
                            ////{

                            ////byte[] dataToWrite = MuLawEncoder.MuLawEncode(memStream.GetBuffer()); //MULAW
                            ////byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer()); //ALAW (RECOMENdADO)
                            ////byte[] dataToWrite = memStream.GetBuffer(); //NORMAL

                            //byte[] dataToWrite;

                            //if (vocoder == Vocoder.ALaw)
                            //    dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer()); //ALAW (RECOMENdADO)
                            //else if (vocoder == Vocoder.uLaw)
                            //    dataToWrite = MuLawEncoder.MuLawEncode(memStream.GetBuffer()); //MULAW
                            //else
                            //    dataToWrite = memStream.GetBuffer();

                            //if (bStop)
                            //    return;

                            byte[] elemento = DispatchData();
                            if (elemento != null)
                            {
                                byte[] dataToWrite;
                                if (vocoder == Vocoder.uLaw)
                                {
                                    dataToWrite = MuLawEncoder.MuLawEncode(elemento);
                                }
                                else if (vocoder == Vocoder.ALaw)
                                {
                                    dataToWrite = ALawEncoder.ALawEncode(elemento);
                                }
                                else
                                {
                                    dataToWrite = elemento;
                                }

                                //byte[] dataToWrite = MuLawEncoder.MuLawEncode(memStream.GetBuffer()); //MULAW
                                //byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer()); //ALAW (RECOMENdADO)
                                //NORMAL

                                if (eMode == Mode.Client)
                                {
                                    cGlobalVars.AddLogChat("3Sending Data!");
                                    udpClient.Send(elemento, elemento.Length, serverIP.Address.ToString(), 1550);
                                }
                                else if (eMode == Mode.Server)
                                {
                                    for (int i = 0; i < users_count; i++)
                                    {
                                        udpClient.Send(elemento, elemento.Length, clientIPs[i].Address.ToString(), 1550);
                                    }
                                }


                                // }
                            }
                        }
                    }
                }

                cGlobalVars.AddLogChat("Sending Ended");
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message, "VoiceChat-Send ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cGlobalVars.AddLogChat("VoiceChat-Send >> " + ex.Message);
            }
            finally
            {
                //captureBuffer.Stop();

                //Increment flag by one.
                nUdpClientFlag += 1;

                //When flag is two then it means we have got out of loops in Send and Receive.
                while (nUdpClientFlag != 2)
                {
                }

                //Clear the flag.
                nUdpClientFlag = 0;

                //Close the socket.
                udpClient.Close();
            }
        }