Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to play real-time audio stream with DirectSound

8 views
Skip to first unread message

Hossein

unread,
Aug 21, 2009, 11:31:47 AM8/21/09
to
I really need some help please.
I'm going to develop a program that plays stream data which are taken from
external device. In this order, I should frequently play the data which is
ready. I know that to play an audio stream in DirectX.DirectSound,
SecondaryBuffer can be used. but my question is that how can I add new audio
stream to SecondaryBuffer instead of destroying the current SecondaryBuffer
and creating new one as I did in my followin code. The code generates
artifacts whenever I call sound.Play(data).
does have anyone any suggestion?

using System;
using System.Windows.Forms;
using Microsoft.DirectX.DirectSound;
using System.IO;

namespace TestSound
{
class CSound : Form
{
const int HEADER_SIZE = 44;
const bool FLAG_STEREO = true;
const short BITS_PER_SAMPLE = 16;
const int SAMPLE_RATE = 44100;

int numberOfSamples;
MemoryStream stream;
BinaryWriter writer;
Device ApplicationDevice = null;
SecondaryBuffer buffer = null;
BufferDescription description;

public CSound()
{
try
{
ApplicationDevice = new Device();
}
catch
{
return;
}
ApplicationDevice.SetCooperativeLevel(this, CooperativeLevel.
Priority);
description = new BufferDescription();
description.ControlEffects = false;
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}

private void AddHeader()
{
stream.Position = 0;

writer.Write(0x46464952); // "RIFF" in ASCII
writer.Write((int)(HEADER_SIZE + (numberOfSamples *
BITS_PER_SAMPLE * (FLAG_STEREO ? 2 : 1) / 8)) - 8);
writer.Write(0x45564157); // "WAVE" in ASCII
writer.Write(0x20746d66); // "fmt " in ASCII
writer.Write(16);
writer.Write((short)1);
writer.Write((short)(FLAG_STEREO ? 2 : 1));
writer.Write(SAMPLE_RATE);
writer.Write(SAMPLE_RATE * (FLAG_STEREO ? 2 : 1) *
BITS_PER_SAMPLE / 8);
writer.Write((short)((FLAG_STEREO ? 2 : 1) * BITS_PER_SAMPLE / 8)
);
writer.Write(BITS_PER_SAMPLE);
writer.Write(0x61746164); // "data" in ASCII
writer.Write((int)(numberOfSamples * BITS_PER_SAMPLE *
(FLAG_STEREO ? 2 : 1) / 8));
}

public void Play(short[] samples)
{
if (ApplicationDevice == null)
return;

stream.Position = HEADER_SIZE;
numberOfSamples = samples.Length;
for (int i = 0; i < numberOfSamples; i++)
{
writer.Write(samples[i]);
if (FLAG_STEREO)
writer.Write(samples[i]);
}
AddHeader();
stream.Position = 0;

try
{
if (buffer != null)
{
buffer.Dispose();
buffer = null;
}
buffer = new SecondaryBuffer(stream, description,
ApplicationDevice);
buffer.Play(0, BufferPlayFlags.Default);
}
catch
{
}
}

public class Test
{
CSound sound = new CSound();
void Run()
{
short[] data;
data = port.Read();
sound.Play(data);
}
}
}
}

url:http://www.ureader.com/gp/1462-1.aspx

0 new messages