Hi @donovan , Welcome to Microsoft Q&A,
The browser needs to know the audio format, so you need to add the WAV file header information at the beginning of the audio stream.
Make sure your audio data is sent to the browser continuously.
- Add WAV header information: In the
ProcessRequest
method, create and send the WAV header information. This header information tells the browser the format of the audio stream.
private async Task ProcessRequest(HttpListenerContext context)
{
HttpListenerResponse response = context.Response;
response.ContentType = "audio/wav";
response.StatusCode = 200;
response.StatusDescription = "OK";
// Create WAV header information
byte[] wavHeader = CreateWavHeader(BWP.WaveFormat, 0);
await response.OutputStream.WriteAsync(wavHeader, 0, wavHeader.Length);
await response.OutputStream.FlushAsync();
byte[] buffer = new byte[BWP.BufferLength];
// Continuously send audio data
while (context.Response.OutputStream.CanWrite)
{
int bytesRead = BWP.Read(buffer, 0, buffer.Length);
await response.OutputStream.WriteAsync(buffer, 0, bytesRead);
await response.OutputStream.FlushAsync();
}
response.OutputStream.Close();
clientTasks.TryRemove(context.Request.RemoteEndPoint.ToString(), out _);
}
- Method to create WAV header information: This method creates a WAV header containing audio format information.
private byte[] CreateWavHeader(WaveFormat format, int dataLength)
{
using (MemoryStream memoryStream = new MemoryStream(44))
using (BinaryWriter writer = new BinaryWriter(memoryStream))
{
int bitsPerSample = format.BitsPerSample;
int bytesPerSecond = format.SampleRate * format.Channels * (bitsPerSample / 8);
short blockAlign = (short)(format.Channels * (bitsPerSample / 8));
writer.Write(Encoding.UTF8.GetBytes("RIFF"));
writer.Write(dataLength + 36);
writer.Write(Encoding.UTF8.GetBytes("WAVE"));
writer.Write(Encoding.UTF8.GetBytes("fmt "));
writer.Write(16);
writer.Write((short)1);
writer.Write((short)format.Channels);
writer.Write(format.SampleRate);
writer.Write(bytesPerSecond);
writer.Write(blockAlign);
writer.Write((short)bitsPerSample);
writer.Write(Encoding.UTF8.GetBytes("data"));
writer.Write(dataLength);
return memoryStream.ToArray();
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.