Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8917439
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T05:29:00+00:00 2026-06-15T05:29:00+00:00

I’m already going crazy. So I decided to ask for help. Scenario: In a

  • 0

I’m already going crazy. So I decided to ask for help.

Scenario: In a web page, connect to the server via TCP socket, and in a loop I get the data byte by byte. These data are continuous.

Question: How do I make a WebSocket that receive and send data to the player ( html5 tag).

Default.aspx

<asp:Literal ID="ltrPlayer" runat="server" />

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    string tele = HttpContext.Current.Request.QueryString["tele"];
    string ramal = HttpContext.Current.Request.QueryString["ramal"];
    string dac = HttpContext.Current.Request.QueryString["dac"];
    string cti = HttpContext.Current.Request.QueryString["cti"];

    if ((tele != null) && (ramal != null) && (dac != null) && (cti != null))
    {
        string strAudio = "<audio controls='controls'>";
        strAudio += "<source src='Play.ashx?tele=" + tele + "&ramal=" + ramal + "&dac=" + dac + "&cti=" + cti + "' type='audio/x-wav' controls preload='auto'>";
        strAudio += "Seu browser não oferece suporte a este player.";
        strAudio += "</audio>";

        ltrPlayer.Text = strAudio;
    }
}

Play.ashx

<%@ WebHandler Language="C#" Class="Play" %>

using System;
using System.Web;

using System.Net;
using System.IO;
using Alvas.Audio; // Make the conversion VOX to WAV
using System.Media;
using System.Configuration;

using System.Net.Sockets;
using System.Text;


public class Play : IHttpHandler
{
    private NetworkStream ns;

    public void ProcessRequest(HttpContext context)
    {
        string tele = HttpContext.Current.Request.QueryString["tele"];
        string ramal = HttpContext.Current.Request.QueryString["ramal"];
        string dac = HttpContext.Current.Request.QueryString["dac"];
        string cti = HttpContext.Current.Request.QueryString["cti"];   

        if ((tele != null) && (ramal != null) && (dac != null) && (cti != null))
        {
            try
            {
                TcpClient oClient = new TcpClient();

                oClient.Connect(tele, 22000);

                ns = oClient.GetStream();
                write(ns, "ondelogar");

                ns = oClient.GetStream();
                write(ns, "monitorarRamalViaRede(tele;ramal;dac;cti)");

                Thread.Sleep(1000);                

                do
                {
                    if (oClient.GetStream().DataAvailable == true)
                    {
                        using (StringReader reader = new StringReader(read(ns)))
                        {
                            string line;

                            while ((line = reader.ReadLine()) != null)
                            {
                                Byte[] byteOut = new Byte[line.Length / 2];

                                int i = 0;
                                while (i < (line.Length / 2))
                                {
                                    byteOut[i / 2] = Convert.ToByte(line.Substring(i, 2), 16);
                                    i = i + 2;
                                }

                                Stream s = new MemoryStream(byteOut);
                                BinaryReader br = new BinaryReader(s);
                                MemoryStream pcmStream = new MemoryStream();
                                IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 6000);
                                WaveWriter ww = new WaveWriter(pcmStream, AudioCompressionManager.FormatBytes(pcmFormat));
                                Vox.Vox2Wav(br, ww);
                                WaveReader wr = new WaveReader(pcmStream);

                                byte[] pcmData = pcmStream.ToArray();

                                br.Close();
                                ww.Close();
                                wr.Close();
                                pcmStream.Close();
                                Array.Clear(byteOut, 0, byteOut.Length);

                                HttpContext.Current.Response.Clear();
                                HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", "BufferDeAudio"));
                                HttpContext.Current.Response.ContentType = "audio/x-wav";
                                HttpContext.Current.Response.BinaryWrite(pcmData);
                                HttpContext.Current.Response.End();             
                            }
                        }
                    }
                }
                while (oClient.GetStream().DataAvailable == true);

                ns.Close();
            }
            catch (Exception)
            {

            }

            HttpContext.Current.Response.End();
        }
    }

    private void write(NetworkStream ns, string message)
    {
        byte[] msg = Encoding.ASCII.GetBytes(message + Environment.NewLine);
        ns.Write(msg, 0, msg.Length);
    }

    private string read(NetworkStream ns)
    {
        StringBuilder sb = new StringBuilder();

        if (ns.CanRead)
        {
            byte[] readBuffer = new byte[1024];

            int numBytesRead = 0;

            do
            {
                numBytesRead = ns.Read(readBuffer, 0, readBuffer.Length);
                sb.AppendFormat("{0}", Encoding.ASCII.GetString(readBuffer, 0, numBytesRead));
                sb.Replace(Convert.ToChar(24), ' ');
                sb.Replace(Convert.ToChar(255), ' ');
                sb.Replace('?', ' ');
            }

            while (ns.DataAvailable);
        }

        return sb.ToString();
        }                                        

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Then, as the loop receives the data line by line, I am sending to the player. But the only sound I hear is the last line of the loop.

I tried to put the player in a thread without success.

Is this possible? Any idea?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T05:29:01+00:00Added an answer on June 15, 2026 at 5:29 am

    After several attempts, finally managed to get a satisfactory result. See the code.

    Play.ashx

    public void ProcessRequest(HttpContext context)
    {
        string tele = HttpContext.Current.Request.QueryString["tele"];
        string ramal = HttpContext.Current.Request.QueryString["ramal"];
        string dac = HttpContext.Current.Request.QueryString["dac"];
        string cti = HttpContext.Current.Request.QueryString["cti"];
    
        if ((tele != null) && (ramal != null) && (dac != null) && (cti != null))
        {
            string strLine = string.Empty;
            string strNewLine = string.Empty;
            int intCountBuffer = 0;
    
            MemoryStream pcmStream = null;
            MemoryStream audioStream = null;
            bool blnArmazenarBuffer = true;
    
            try
            {
                TcpClient oClient = new TcpClient();
                oClient.Connect(tele, 22000);
    
                ns = oClient.GetStream();
                write(ns, "ondelogar");
    
                ns = oClient.GetStream();
                write(ns, "monitorarRamalViaRede(" + tele + ";" + ramal + ";" + dac + ";" + cti + ")");
    
                Thread.Sleep(1000);
    
    
    
    
                context.Response.ClearContent();
                context.Response.ClearHeaders();
                context.Response.BufferOutput = false;
                context.Response.AddHeader("Content-Disposition", "attachment; filename=Gravacao");
                context.Response.ContentType = "audio/x-wav";
    
                int readCount;
                byte[] data = new byte[oClient.ReceiveBufferSize];
    
                while ((readCount = ns.Read(data, 0, oClient.ReceiveBufferSize)) != 0)
                {
                    using (StringReader readerTest = new StringReader(read(ns)))
                    {
                        strLine = readerTest.ReadLine();
    
                        if (strLine.Substring(0, 13) == "BufferDeAudio")
                        {
                            strLine = strLine.Replace("BufferDeAudio(", string.Empty);
                            strLine = strLine.Replace(")", string.Empty);
                            strLine = strLine.Replace(" ", string.Empty);
                            strLine = strLine.Trim();
    
                            if (blnArmazenarBuffer == true)
                            {
                                strNewLine += strLine;
                                intCountBuffer++;
    
                                // Holds 10 packages (or 10 seconds) in buffer
                                // Note: Only for ensuring that the first transmission is delivered.
                                if (intCountBuffer >= 10)
                                {
                                    pcmStream = VoxToWav(strNewLine);
                                    strNewLine = string.Empty;
    
                                    // ChunkSize
                                    // Note. See the documentation on: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
                                    pcmStream.Position = 4;
                                    pcmStream.WriteByte(12);
    
                                    pcmStream.Position = 5;
                                    pcmStream.WriteByte(77);
    
                                    pcmStream.Position = 6;
                                    pcmStream.WriteByte(104);
    
                                    pcmStream.Position = 7;
                                    pcmStream.WriteByte(28);
    
                                    // SubChunk2Size
                                    pcmStream.Position = 40;
                                    pcmStream.WriteByte(232);
    
                                    pcmStream.Position = 41;
                                    pcmStream.WriteByte(76);
    
                                    pcmStream.Position = 42;
                                    pcmStream.WriteByte(104);
    
                                    pcmStream.Position = 43;
                                    pcmStream.WriteByte(28);
    
                                    if (context.Response.IsClientConnected)
                                    {
                                        // The first time you step through the loop, i send wav header
                                        audioStream = new MemoryStream();
    
                                        audioStream.Position = 0;
                                        pcmStream.Position = 0;
                                        audioStream.Write(pcmStream.ToArray(), 0, (Int32)pcmStream.Length);
                                    }
    
                                    blnArmazenarBuffer = false;
                                }
                            }
                            else
                            {
                                pcmStream = VoxToWav(strLine);
                                strLine = string.Empty;
    
                                if (context.Response.IsClientConnected)
                                {
                                    // Here I have already sent the header. So no need to send it over again.
                                    audioStream = new MemoryStream();
    
                                    byte[] arr1 = pcmStream.ToArray();
    
                                    int x = 44;
    
                                    while (x < (arr1.Length))
                                    {
                                        audioStream.Position = x - 44;
                                        audioStream.WriteByte(arr1[x]);
    
                                        x++;
                                    }
                                }
                            }
    
                            context.Response.OutputStream.Write(audioStream.ToArray(), 0, (Int32)audioStream.Length);
                            context.Response.OutputStream.Flush();
                            context.Response.OutputStream.Close();
    
                            audioStream.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (File.Exists(path))
                {
                    StreamWriter w = File.AppendText(path);
    
                    w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
                    w.WriteLine("  :");
                    w.WriteLine("  :{0}", "Play.ashx");
                    w.WriteLine("  :{0}", ex.Message);
                    w.WriteLine("-------------------------------");
    
                    w.Flush();
                    w.Close();
                }
            }
    
            ns.Close();
        }
    }
    
    private void write(NetworkStream ns, string message)
    {
        byte[] msg = Encoding.ASCII.GetBytes(message + Environment.NewLine);
        ns.Write(msg, 0, msg.Length);
    }
    
    private string read(NetworkStream ns)
    {
        StringBuilder sb = new StringBuilder();
    
        if (ns.CanRead)
        {
            byte[] readBuffer = new byte[1024];
    
            int numBytesRead = 0;
    
            do
            {
                numBytesRead = ns.Read(readBuffer, 0, readBuffer.Length);
                sb.AppendFormat("{0}", Encoding.ASCII.GetString(readBuffer, 0, numBytesRead));
                sb.Replace(Convert.ToChar(24), ' ');
                sb.Replace(Convert.ToChar(255), ' ');
                sb.Replace('?', ' ');
            }
    
            while (ns.DataAvailable);
        }
    
        return sb.ToString();
    }
    
    private MemoryStream VoxToWav(string strLine)
    {
        //How do I get the data in hexadecimal. This trick is to order them in pairs.
        byte[] byteOut = new byte[strLine.Length / 2];
    
        int j = 0;
        while (j < (strLine.Length))
        {
            byteOut[j / 2] = Convert.ToByte(strLine.Substring(j, 2), 16);
            j = j + 2;
        }
    
        Stream s = new MemoryStream(byteOut);
        BinaryReader br = new BinaryReader(s);
        MemoryStream pcmStream = new MemoryStream();
        IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 6000);
        WaveWriter ww = new WaveWriter(pcmStream, AudioCompressionManager.FormatBytes(pcmFormat));
        Vox.Vox2Wav(br, ww);
    
        return pcmStream;
    }
    
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    

    Thank you all!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm making a simple page using Google Maps API 3. My first. One marker
I'm interested in microtypography issues on the web. I want a tool to fix:
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.