• Advertisement
Sign in to follow this  

Capture Audio - managed DirectSound -

This topic is 4258 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi, i want to capture live audio from microphone and play it live at my loudspeakers! later i want to stream (with udp) the live audio to another pc and play it there... i used the the sample: capture sound (managed) from the directx sample browser and added some code! i cant hear anything;/ why? i will only post the function where i added some code:
public class MainForm : Form
{
    .......
    .......

    /********************************* added by me ************************************************/    
    public Device soundDevice = null;
/**********************************************************************************************/


	private void InitDirectSound()
	{
        /********************************* added by me ************************************************/

        soundDevice = new Device();
        soundDevice.SetCooperativeLevel(this, CooperativeLevel.Priority);

        /**********************************************************************************************/

		CaptureBufferSize = 0;
		NotifySize = 0;

		// Create DirectSound.Capture using the preferred capture device
		try
		{
			applicationDevice = new Capture(CaptureDeviceGuid);
		}
		catch {}
	}
	void CreateCaptureBuffer()
	{
		//-----------------------------------------------------------------------------
		// Name: CreateCaptureBuffer()
		// Desc: Creates a capture buffer and sets the format 
		//-----------------------------------------------------------------------------
		CaptureBufferDescription dscheckboxd = new CaptureBufferDescription(); 

		if (null != applicationNotify)
		{
			applicationNotify.Dispose();
			applicationNotify = null;
		}
		if (null != applicationBuffer)
		{
			applicationBuffer.Dispose();
			applicationBuffer = null;
		}

		if (0 == InputFormat.Channels)
			return;

		// Set the notification size
		NotifySize = (1024 > InputFormat.AverageBytesPerSecond / 8) ? 1024 : (InputFormat.AverageBytesPerSecond / 8);
		NotifySize -= NotifySize % InputFormat.BlockAlign;   

		// Set the buffer sizes
		CaptureBufferSize = NotifySize * NumberRecordNotifications;

		// Create the capture buffer
		dscheckboxd.BufferBytes = CaptureBufferSize;
		InputFormat.FormatTag = WaveFormatTag.Pcm;
		dscheckboxd.Format = InputFormat; // Set the format during creatation
		
		applicationBuffer = new CaptureBuffer(dscheckboxd, applicationDevice);
		NextCaptureOffset = 0;

		InitNotifications();
	}


	void RecordCapturedData() 
	{
		//-----------------------------------------------------------------------------
		// Name: RecordCapturedData()
		// Desc: Copies data from the capture buffer to the output buffer 
		//-----------------------------------------------------------------------------
		byte[] CaptureData = null;
		int ReadPos;
		int CapturePos;
		int LockSize;

		applicationBuffer.GetCurrentPosition(out CapturePos, out ReadPos);
		LockSize = ReadPos - NextCaptureOffset;
		if (LockSize < 0)
			LockSize += CaptureBufferSize;

		// Block align lock size so that we are always write on a boundary
		LockSize -= (LockSize % NotifySize);

		if (0 == LockSize)
			return;

		// Read the capture buffer.
		CaptureData = (byte[])applicationBuffer.Read(NextCaptureOffset, typeof(byte), LockFlag.None, LockSize);

        /********************************* added by me ***************************************/

        WaveFormat format = new WaveFormat();
        format.BitsPerSample = 8;
        format.Channels = 1;
        format.BlockAlign = 1;

        format.FormatTag = WaveFormatTag.Pcm;
        format.SamplesPerSecond = 8000; //sampling frequency of your data;
        format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlign;

        // buffer description
        BufferDescription desc = new BufferDescription(InputFormat/*format*/);
        desc.DeferLocation = true;
        desc.BufferBytes = 3 * format.AverageBytesPerSecond;

        SecondaryBuffer soundBuffer = new SecondaryBuffer(desc, soundDevice);
        //load audio samples to secondary buffer
        soundBuffer.Write(0, CaptureData, LockFlag.EntireBuffer);

        //play audio buffer
        soundBuffer.Play(0, BufferPlayFlags.Looping);

        /**********************************************************************************************/

		// Write the data into the wav file
		Writer.Write(CaptureData, 0, CaptureData.Length);
		
		// Update the number of samples, in bytes, of the file so far.
		SampleCount += CaptureData.Length;

		// Move the capture offset along
		NextCaptureOffset += CaptureData.Length; 
		NextCaptureOffset %= CaptureBufferSize; // Circular buffer
	}


here i added the project: Source [Edited by - Surfman19 on June 24, 2006 8:19:01 AM]

Share this post


Link to post
Share on other sites
Advertisement
hello, could someone test my new code?
how does the applicationNotify and NotificationEvent work?
why do i always hear a little noise?hmmm?
how could i read the applicationBuffer into a MemoryStream and write it into soundBuffer???

bye


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using Microsoft.DirectX.DirectSound;

namespace Noisey
{
/// <summary>
/// Very simple test form
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button buttonStart;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public BufferPositionNotify[] PositionNotify = new BufferPositionNotify[NumberRecordNotifications + 1];
public const int NumberRecordNotifications = 16;
public AutoResetEvent NotificationEvent = null;
public Notify applicationNotify = null;
public int CaptureBufferSize = 0;
public int NextCaptureOffset = 0;
private bool Recording = false;
private int SampleCount = 0;
public int NotifySize = 0;
private bool Capturing = false;

public WaveFormat InputFormat;
public CaptureDevicesCollection devices = null;
public Capture applicationDevice = null;
public CaptureBuffer applicationBuffer = null;
public Device soundDevice = null;
public BufferDescription desc = null;
public SecondaryBuffer soundBuffer = null;

private Thread SoundStreamingThread = null;

public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// Add any constructor code after InitializeComponent call
//
CaptureBufferSize = 0;
NotifySize = 0;

devices = new CaptureDevicesCollection();
applicationDevice = new Capture(devices[1].DriverGuid);

InputFormat = new WaveFormat();
InputFormat.AverageBytesPerSecond = 8000;
InputFormat.BitsPerSample = 8;
InputFormat.BlockAlign = 1;
InputFormat.Channels = 1;
InputFormat.FormatTag = WaveFormatTag.Pcm;
InputFormat.SamplesPerSecond = 8000;

if (null != applicationNotify)
{
applicationNotify.Dispose();
applicationNotify = null;
}
if (null != applicationBuffer)
{
applicationBuffer.Dispose();
applicationBuffer = null;
}

if (0 == InputFormat.Channels)
return;

CaptureBufferDescription dscheckboxd = new CaptureBufferDescription();

// Set the notification size
NotifySize = (1024 > InputFormat.AverageBytesPerSecond / 8) ? 1024 : (InputFormat.AverageBytesPerSecond / 8);
NotifySize -= NotifySize % InputFormat.BlockAlign;

// Set the buffer sizes
CaptureBufferSize = NotifySize * NumberRecordNotifications;

// Create the capture buffer
dscheckboxd.BufferBytes = CaptureBufferSize;
dscheckboxd.Format = InputFormat; // Set the format during creatation

applicationBuffer = new CaptureBuffer(dscheckboxd, applicationDevice);
NextCaptureOffset = 0;

soundDevice = new Device();
soundDevice.SetCooperativeLevel(this, CooperativeLevel.Normal);

// buffer description
desc = new BufferDescription(InputFormat/*format*/);
desc.DeferLocation = true;
desc.BufferBytes = 3 * InputFormat.AverageBytesPerSecond;

soundBuffer = new SecondaryBuffer(desc, soundDevice);
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.buttonStart = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// buttonStart
//
this.buttonStart.Location = new System.Drawing.Point(64, 87);
this.buttonStart.Name = "buttonStart";
this.buttonStart.Size = new System.Drawing.Size(172, 27);
this.buttonStart.TabIndex = 0;
this.buttonStart.Text = "Start";
this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(292, 260);
this.Controls.Add(this.buttonStart);
this.Name = "MainForm";
this.Text = "SoundStreaming";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}


private void buttonStart_Click(object sender, System.EventArgs e)
{
// Create a notification event, for when the sound stops playing
NotificationEvent = new AutoResetEvent(false);

// Setup the notification positions
for (int i = 0; i < NumberRecordNotifications; i++)
{
PositionNotify.Offset = (NotifySize * i) + NotifySize - 1;
PositionNotify.EventNotifyHandle = NotificationEvent.Handle;
}

applicationNotify = new Notify(applicationBuffer);

// Tell DirectSound when to notify the app. The notification will come in the from
// of signaled events that are handled in the notify thread.
applicationNotify.SetNotificationPositions(PositionNotify, NumberRecordNotifications);

//Recording = true;

SoundStreamingThread = new Thread(new ThreadStart(WaitThread));
Capturing = true;
applicationBuffer.Start(true);
SoundStreamingThread.Start();
}

private void RecordCapturedData()
{
byte[] CaptureData = null;
int ReadPos;
int CapturePos;
int LockSize;

applicationBuffer.GetCurrentPosition(out CapturePos, out ReadPos);
LockSize = ReadPos - NextCaptureOffset;
if (LockSize < 0)
LockSize += CaptureBufferSize;

// Block align lock size so that we are always write on a boundary
LockSize -= (LockSize % NotifySize);

if (0 == LockSize)
return;

// Read the capture buffer.
CaptureData = (byte[])applicationBuffer.Read(NextCaptureOffset, typeof(byte), LockFlag.None, LockSize);

// Load audio samples to secondary buffer
soundBuffer.Write(0, CaptureData, LockFlag.EntireBuffer);

soundBuffer.SetCurrentPosition(0);

// Play audio buffer
soundBuffer.Play(0, BufferPlayFlags.Looping);

// Move the capture offset along
NextCaptureOffset += CaptureData.Length;
NextCaptureOffset %= CaptureBufferSize; // Circular buffer
}

private void WaitThread()
{
while (Capturing)
{
//Sit here and wait for a message to arrive
NotificationEvent.WaitOne(Timeout.Infinite, true);
RecordCapturedData();
}
}
}
}




[Edited by - Surfman19 on June 24, 2006 6:44:46 PM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement