Reputation: 273
I am trying to stream audio bytes into an naudio waveout stream but it isn't working. Here is the pseudocode:
byte[] by = new byte[2560] //audio packet sizes
int counter=0;
while (true) { //keep receiving bytes from incoming TCP socket
int bytesAvailable = await stream.ReadAsync(by, 0, 2560); //read incoming bytes
if(counter==0) {
using (var MemoryStream = new MemoryStream(by)) {
var waveOut = new WaveOut();
var waveFormat = new WaveFormat(16000, 16, 2); // wave format
var rawSource = new RawSourceWaveStream(MemoryStream, waveFormat);
waveOut.Init(rawSource);
waveOut.Play();
counter++;
}
}
..but I am not hearing anything. I am guessing it just reads one packet and stops, but I don't know.
Anyone know what is wrong/how to fix? I know the bytes are coming in because I print out the last byte so it's nothing to do with the network receive.
Upvotes: 0
Views: 4248
Reputation: 273
for Ortund:
private async void StartClient()
{
String sName = "<server ip>";
int port = <server port>;
WaveOut waveout = new WaveOut();
TcpClient conn = new TcpClient();
try
{
int counter = 0;
conn.Connect(sName, port);
stream = conn.GetStream();
by = new byte[2560]; // new byte array to store received data
var bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(16000, 16, 2));
bufferedWaveProvider.BufferLength = 2560 * 16; //16 is pretty good
bufferedWaveProvider.DiscardOnBufferOverflow = true;
while (true)
{
//wait until buffer has data, then returns buffer length
int bytesAvailable = await stream.ReadAsync(by, 0, 2560);
if (counter == 0)
{
msg = Encoding.UTF8.GetString(by, 0, bytesAvailable);
devicehash = msg.TrimEnd();
DispatchMethod(by[0].ToString());
counter++;
}
else
{
//send to speakers
bufferedWaveProvider.AddSamples(by, 0, 2560);
if (counter == 1)
{
waveout.Init(bufferedWaveProvider);
waveout.Play();
counter++;
}
}
}
}
catch (Exception e)
{
}
}
Upvotes: 1
Reputation: 49482
it would be better to use a BufferedWaveProvider
for this. Just create a single WaveOut
device that is playing from the BufferedWaveProvider
, and add the byte array of received data to the BufferedWaveProvider
as it arrives over the network.
Upvotes: 2