D
D
DerilH2021-11-07 18:04:54
C++ / C#
DerilH, 2021-11-07 18:04:54

How to make the received sound play continuously, like in a voice chat?

There is such a code written using sockets and NAudio

public void BeginReceive() 
        {
            Thread ReceiveVoiceFromChatThread = new Thread(()=> 
            {
                while (true) 
                {
                    try
                    {
                        byte[] ReceivedVoiceDataLenght = new byte[4];
                        VoiceSocket.Receive(ReceivedVoiceDataLenght);
                        byte[] ReceivedVoiceData = new byte[BitConverter.ToInt32(ReceivedVoiceDataLenght)];
                        VoiceSocket.Receive(ReceivedVoiceData);
                        new Thread(() =>
                        {
                            try
                            {
                                IWaveProvider provider = new RawSourceWaveStream(new MemoryStream(ReceivedVoiceData), new WaveFormat(44100, 1));
                                WaveOut _waveOut = new();
                                _waveOut.Init(provider);
                                _waveOut.Play();
                            }
                            catch (Exception ex) 
                            {
                                MessageBox.Show(ex.ToString());
                            }
                        }).Start();
                   

                    }
                    catch(Exception ex) 
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            });
            ReceiveVoiceFromChatThread.Start();
        }

I know, the code is very crooked, and should not work as it should. But it does not work in principle, every 40 milliseconds an array of bytes from the socket arrives there, but for some reason the sound is not played.
PS TCP socket is used (also not the best choice).

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question