Capture Sound from microphone using Directx DirectSound - c#

I am creating a simple application that records input from the microphone and store it into array of bytes. So I have searched a lot about this and eventually ended up using Directx DirectSound. Here is the code I am using:
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
private Thread CaptureSoundThread = null;
public CaptureBuffer applicationBuffer = null;
private SecondaryBuffer soundBuffer = null;
private Device soundDevice = null;
private void Form1_Load(object sender, EventArgs e)
{
soundDevice = new Device();
soundDevice.SetCooperativeLevel(this, CooperativeLevel.Normal);
// Set up our wave format to 44,100Hz, with 16 bit resolution
WaveFormat wf = new WaveFormat();
wf.FormatTag = WaveFormatTag.Pcm;
wf.SamplesPerSecond = 44100;
wf.BitsPerSample = 16;
wf.Channels = 1;
wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8);
wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign;
int samplesPerUpdate = 512;
// Create a buffer with 2 seconds of sample data
BufferDescription bufferDesc = new BufferDescription(wf);
bufferDesc.BufferBytes = samplesPerUpdate * wf.BlockAlign * 2;
bufferDesc.ControlPositionNotify = true;
bufferDesc.GlobalFocus = true;
soundBuffer = new SecondaryBuffer(bufferDesc, soundDevice);
}
private void button1_Click(object sender, EventArgs e)
{
CaptureSoundThread = new Thread(new ThreadStart(WaitThread));
CaptureSoundThread.Start();
}
private void WaitThread()
{
while (true)
{
byte[] CaptureData = null;
CaptureData = (byte[])applicationBuffer.Read(0,
typeof(byte), LockFlag.None);
soundBuffer.Write(0, CaptureData, LockFlag.None);
// Start it playing
soundBuffer.Play(0, BufferPlayFlags.Looping);
}
}
But when I try to run the application, I get this annoying error:
BadImageFormatException
Could not load file or assembly 'Microsoft.DirectX.DirectSound.dll' or one
of its dependencies. is not a valid Win32 application. (Exception from
HRESULT: 0x800700C1)
I actually had to download the Microsoft.DirectX.DirectSound.dll from the internet because I couldn't find them in the Visual Studio assemblies.
EDIT : I JUST SOLVED THAT by reading this article : http://www.codeproject.com/Articles/383138/BadImageFormatException-x86-i-x64

EDIT : I JUST SOLVED THAT by reading this article : http://www.codeproject.com/Articles/383138/BadImageFormatException-x86-i-x64

Related

C# App Installer - installed App not opening

I have created Setup.exe of my Application in Visual Studio 2019, using C#, in my computer. I installed the app in another laptop, by copying the debug folder with setup files, to that laptop. But, after installation, when I clicked the App, it is not opening. I have also tried changing the target dotnet frame work of application in Visual Studio, to match with the laptop. But same effect. This App have references to some external dll files such as a spectrometer related dlls and the tool mathematica's dll. If everything works fine, this App is supposed to collect data from spectrometer and do signal processing and display results at dotnet GUI.
References and dlls used
Ocean Optics Spectrometer related - common64.dll, NETOmniDriver-NET40.dll
Wolfram Mathemtica tool related - ml32i4.dll, Wolfram.NETLink.dll
Please help me in opening my App.
Please find code below.
namespace JointApp1
{
public partial class Form1 : Form
{
int numberOfSpectrometersFound;
int spectrometerIndex; // indicates which spectrometer we are using
OmniDriver.CCoWrapper wrapper;
private Wolfram.NETLink.MathKernel mathKernel;
public Form1(string[] args)
{
InitializeComponent(args);
wrapper = new OmniDriver.CCoWrapper();
spectrometerIndex = -1;
}
private void button5_Click(object sender, EventArgs e)
{
numberOfSpectrometersFound = wrapper.openAllSpectrometers();
if (numberOfSpectrometersFound < 1)
{
listBox1.Items.Add("No spectrometers found");
spectrometerIndex = -1; // set it to an invalid value
return;
}
spectrometerIndex = 0; // arbitrarily choose the first
// spectrometer for this demo
listBox1.Items.Add("Selecting spectrometer: " +
wrapper.getName(spectrometerIndex));
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"C:\Program Files\Wolfram Research\Mathematicanew\12.0\SystemFiles\Links\NETLink\Examples\Part1\MathKernelApp\JointApps\rd.csv");
string line;
if (sr != null) sr.Close();
//end of graph
int numberOfPixels; // number of CCD elements/pixels provided by the spectrometer
double[] spectrum;
if (spectrometerIndex == -1)
return; // no available spectrometer
numberOfPixels = wrapper.getNumberOfPixels(spectrometerIndex);
// Set some acquisition parameters and then acquire a spectrum
spectrum = (double[])wrapper.getSpectrum(spectrometerIndex);
// Display the raw pixel values of this spectrum
var csv = new StringBuilder();
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Imprint KGT\Documents\Visual Studio 2012\editingg for lamda\WindowsFormsApplication1\wn.txt");
for (int i = 0; i < numberOfPixels; ++i)
{
double[] array = new double[1044];
var first = spectrum[i].ToString();
var newLine = string.Format("{0},{1}",lines[i], first);
csv.AppendLine(newLine);
}
File.WriteAllText((#"C:\Program Files\Wolfram Research\Mathematicanew\12.0\SystemFiles\qwer.csv"), csv.ToString());
for (int index = 0; index < numberOfPixels; ++index)
{
listBox2.Items.Add("Raman Shift[" + lines[index] + "] = " +
spectrum[index]);
double qw = spectrum[1];
}
}
private async void Button4_Click(object sender, System.EventArgs e)
{
statusStrip1.Text = "calling mathematica.......detecting pesticide presence.....";
if (mathKernel.IsComputing) { mathKernel.Abort(); }
else
{
try
{
mathKernel.Compute("linkName = \"Bob\"");
mathKernel.Compute("remoteLinkObj = LinkOpen[linkName, LinkMode -> Listen]");
mathKernel.Compute("Needs[\"JLink`\"]");
mathKernel.Compute("$FrontEndLaunchCommand = \"C:\\Program Files\\Wolfram Research\\Mathematicanew\\12.0\\Mathematica.exe\"");
mathKernel.Compute("UseFrontEnd[nb = CreateDocument[Null, Visible -> False]; NotebookWrite[nb, Cell[BoxData[{RowBox[{RowBox[{\"linkName\", \"=\", \"\\\"Bob\\\"\"}], \";\"}], \" \", RowBox[{RowBox[{\"feLinkObject\", \"=\", RowBox[{\"LinkOpen\", \"[\", RowBox[{\"linkName\", \",\", RowBox[{\"LinkMode\", \"\\[Rule]\", \"Connect\"}]}], \"]\"}]}], \";\"}], \" \", RowBox[{RowBox[{\"SetAttributes\", \"[\", RowBox[{\"remoteEval\", \",\", \"HoldRest\"}], \"]\"}], \";\"}], \" \", RowBox[{RowBox[{RowBox[{\"remoteEval\", \"[\", RowBox[{\"link_LinkObject\", \",\", \"expr_\"}], \"]\"}], \":=\", RowBox[{\"(\", RowBox[{RowBox[{\"LinkWrite\", \"[\", RowBox[{\"link\", \",\", RowBox[{\"Unevaluated\", \"[\", \"expr\", \"]\"}]}], \"]\"}], \";\", RowBox[{\"LinkRead\", \"[\", \"link\", \"]\"}]}], \")\"}]}], \";\"}]}], \"Input\"]]; SelectionMove[nb, Previous, Cell]; SelectionEvaluate[nb]; NotebookClose[nb]]");
mathKernel.Compute("NotebookEvaluate[\"greenchillicode.nb\"]");
string a = mathKernel.Result.ToString();
//la
textBox1.Text = a;
mathKernel.Compute("evalLoop[link_LinkObject] := Module[{resultOfEval, exprIn, exprOut, evalMessages}, evalMessages = {}; collectMessages[m_] := AppendTo[evalMessages, m]; Internal`AddHandler[\"Message\", collectMessages]; While[True, evalMessages = {}; exprIn = LinkRead[link, Hold]; resultOfEval = Check[exprOut = ReleaseHold[exprIn], $Failed]; Which[resultOfEval === $Failed, LinkWrite[link, EvalError[\"In\" -> exprIn, \"Out\" -> exprOut, \"Messages\" -> evalMessages]], True, LinkWrite[link, exprOut]]]; Internal`RemoveHandler[\"Message\", collectMessages]; LinkWrite[link, \"Evaluation loop is off\"]]");
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
}
private void Show(System.Drawing.Image image)
{
throw new System.NotImplementedException();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.SuspendLayout();
//
// Form1
//
this.ClientSize = new System.Drawing.Size(1378, 744);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "23april";
this.ResumeLayout(false);
}
}
}

How can i extract frames from video using directshowlib-2005?

With this code i can play video files from my hard disk and show the video in pictureBox1. But i wonder how can i save all the frames of the video to images files on the hard disk ? While playing the video or without playing i need somehow to extract the frames and save them.
This is my used code so far:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
IGraphBuilder m_graphBuilder = null;
IMediaControl m_mediaCtrl = null;
IMediaEventEx m_mediaEvt = null;
IMediaPosition m_mediaPos = null;
IMediaSeeking m_mediaSeeking = null;
public Form1()
{
InitializeComponent();
}
void InitInterfaces()
{
try
{
m_graphBuilder = (IGraphBuilder)new FilterGraph();
m_mediaCtrl = (IMediaControl)m_graphBuilder;
m_mediaEvt = (IMediaEventEx)m_graphBuilder;
m_mediaPos = (IMediaPosition)m_graphBuilder;
m_mediaSeeking = (IMediaSeeking)m_graphBuilder;
}
catch (Exception)
{
MessageBox.Show("Couldn't start directshow graph");
}
}
void CloseInterfaces()
{
if (m_mediaCtrl != null)
{
m_mediaCtrl.StopWhenReady();
}
m_mediaCtrl = null;
m_mediaEvt = null;
m_mediaPos = null;
m_mediaSeeking = null;
if (m_graphBuilder != null)
Marshal.ReleaseComObject(this.m_graphBuilder);
m_graphBuilder = null;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void SetuupVideoRenderer()
{
IBaseFilter vmrFilter = null;
vmrFilter = (IBaseFilter)new VideoMixingRenderer();
m_graphBuilder.AddFilter(vmrFilter, "Video Renderer");
IVMRFilterConfig FilterConfig = (IVMRFilterConfig)vmrFilter;
FilterConfig.SetRenderingMode(VMRMode.Windowless);
IVMRWindowlessControl windowlessCtrl = (IVMRWindowlessControl)vmrFilter;
windowlessCtrl.SetVideoClippingWindow(this.pictureBox1.Handle);
windowlessCtrl.SetVideoPosition(null, DsRect.FromRectangle(pictureBox1.ClientRectangle));
windowlessCtrl.SetAspectRatioMode(VMRAspectRatioMode.LetterBox);
}
private void buttonLoad_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "All Files (*.*)|*.*|mp4 (*.mp4)|*.mp4|mov (*.mov)|*.mov||";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
CloseInterfaces();
InitInterfaces();
SetuupVideoRenderer();
m_graphBuilder.RenderFile(openFileDialog1.FileName, null);
textBoxDur.Text = ( getDuration() * 0.0000001).ToString();
m_mediaCtrl.Run();
timer1.Enabled = true;
}
}
private void GetPosition(out long CurrentPos,out long StopPos)
{
m_mediaSeeking.GetPositions(out CurrentPos, out StopPos);
}
private long getDuration()
{
long duration;
m_mediaSeeking.GetDuration(out duration);
return duration;
}
private void SetPos(double fPos)
{
DsLong startPosition = (DsLong)(10000000 * fPos);
m_mediaSeeking.SetPositions(startPosition, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning);
}
private void buttonPause_Click(object sender, EventArgs e)
{
m_mediaCtrl.Pause();
}
private void buttonPlay_Click(object sender, EventArgs e)
{
m_mediaCtrl.Run();
}
private void OnVideoCompleted()
{
MessageBox.Show("Video Playback Completed");
}
private void timer1_Tick(object sender, EventArgs e)
{
long iCurPos, iStopPos;
GetPosition(out iCurPos, out iStopPos);
if (iCurPos >= iStopPos)
{
timer1.Enabled = false;
OnVideoCompleted();
return;
}
textBoxCurPos.Text = (iCurPos * 0.0000001 ).ToString();
}
private void buttonGo_Click(object sender, EventArgs e)
{
SetPos(Convert.ToDouble(textBoxNewPos.Text));
timer1.Enabled = true;
}
}
}
I think this is excatly what you are looking for:
extract frames of a video
Have a look as well at this SO question and the links provided on this webpage.
The easiest way to do it is indeed using an FFMPEG, since its alredy includes some of the most common codecs (if you dont mind extra 30+Mb added to your app). As for wrappers, i used AForge wrapper in the past and really liked it, because of how simple it is to work with. Here is an example from its docs:
// create instance of video reader
VideoFileReader reader = new VideoFileReader();
// open video file
reader.Open( "test.avi");
// read 100 video frames out of it
for ( int i = 0; i < 100; i++)
{
Bitmap videoFrame = reader.ReadVideoFrame();
videoFrame.Save(i + ".bmp")
// dispose the frame when it is no longer required
videoFrame.Dispose( );
}
reader.Close();

C# Backgroundworker download progress in label, get bytes in label

I've created an application that patches my game servers files.
However, I've got 3 problems which I can't solve:
When downloading a new patch, it doesn't update the progressbar instantly, but refreshes it after around 30-40 seconds
I want a label to show how much mega bytes they are downloading, and how much they have so far (for example: 122Mb/750Mb
When downloading, I want a label to show ~% of how much it has downloaded so far
I am not sure how to add number 2 and 3, and the number 1 problem just seems ridiculous, because there's nothing that indicates it should refresh after 30-40 seconds in my coding (at least as far as I know)
My backgroundWorker1_DoWork:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Defines the server's update directory
string Server = "http://localhost/dl/game-updates/";
//Defines application root
string Root = AppDomain.CurrentDomain.BaseDirectory;
//Make sure version file exists
FileStream fs = null;
if (!File.Exists("version"))
{
using (fs = File.Create("version"))
{
}
using (StreamWriter sw = new StreamWriter("version"))
{
sw.Write("1.0");
}
}
//checks client version
string lclVersion;
using (StreamReader reader = new StreamReader("version"))
{
lclVersion = reader.ReadLine();
}
decimal localVersion = decimal.Parse(lclVersion);
//server's list of updates
XDocument serverXml = XDocument.Load(#Server + "Updates.xml");
//The Update Process
foreach (XElement update in serverXml.Descendants("update"))
{
string version = update.Element("version").Value;
string file = update.Element("file").Value;
decimal serverVersion = decimal.Parse(version);
string sUrlToReadFileFrom = Server + file;
string sFilePathToWriteFileTo = Root + file;
if (serverVersion > localVersion)
{
Uri url = new Uri(sUrlToReadFileFrom);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
Int64 iSize = response.ContentLength;
Int64 iRunningByteTotal = 0;
using (System.Net.WebClient client = new System.Net.WebClient())
{
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
{
using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
{
int iByteSize = 0;
byte[] byteBuffer = new byte[iSize];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
streamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);
backgroundWorker1.ReportProgress(iProgressPercentage);
}
streamLocal.Close();
}
streamRemote.Close();
}
}
//unzip
using (ZipFile zip = ZipFile.Read(file))
{
foreach (ZipEntry zipFiles in zip)
{
zipFiles.Extract(Root + "\\", true);
}
}
//download new version file
WebClient webClient = new WebClient();
webClient.DownloadFile(Server + "version.txt", #Root + "version");
//Delete Zip File
deleteFile(file);
}
}
}
My backgroundWorker1_ProgressChanged:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = "Downloading updates...";
}
And my backgroundWorker1_RunWorkerCompleted:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
settings_btn.Enabled = true;
start_btn_disabled.Enabled = false;
start_btn_disabled.Visible = false;
start_btn.Visible = true;
start_btn.Enabled = true;
progressBar1.Value = 100;
label1.Text = "Client is up to date!";
}
Also, a side note: I'm also having a bit problems of updating labels in backgroundWorker2_DoWork?
Any ideas?
Here's some working code which updates a label on Form1 using the BackgroundWorker.
Create a new Windows Form project and drop it in your code and it'll work.
It's super ugly, but it works.
After that, just plug your code into the DoWork method and calculate your value and send to ReportProgress.
Keep in mind that the work done in DoWork method is the actual Background Thread.
That means that in that method (DoWork) you cannot access UI (form) elements because they are on the UI thread.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.ProgressPercentage.ToString();
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FakeCountingWork();
}
private void FakeCountingWork()
{
int totalNumber = 100;
int progressCounter = 0;
while (progressCounter < totalNumber)
{
int fakecounter = 0;
for (int x = 0; x < 100000000; x++)
{
fakecounter++;
}
progressCounter++;
backgroundWorker1.ReportProgress(progressCounter);
}
}
}
################################## EDITED TO ADD OTHER FUNCTIONALITY
Okay, here's how you can implement a label which displays the number of bytes downloaded so far.
Add a second label named label2 to your form.
Next alter the following methods from my previous example.
Here we are going to use the UserState to pass an extra value to the ProgressChanged Event. It's very simple. You can see that I'm generating a random number and it will now appear in Label2. This is where you could show your number of bytes.
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.ProgressPercentage.ToString();
label2.Text = e.UserState.ToString();
}
private void FakeCountingWork()
{
int totalNumber = 100;
int progressCounter = 0;
Random rnd = new Random();
while (progressCounter < totalNumber)
{
int fakecounter = 0;
for (int x = 0; x < 100000000; x++)
{
fakecounter++;
}
progressCounter++;
updateValue = rnd.Next();
backgroundWorker1.ReportProgress(progressCounter,updateValue);
}
}
I would imagine this is because you are trying to update UI objects on a different thread. HAve you tried using the Dispatcher if using wpf? https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.invoke(v=vs.110).aspx
or Invoke if using Winforms? https://msdn.microsoft.com/fr-ca/library/zyzhdc6b(v=vs.85).aspx
Edit:
As #daylight pointed out to be, the UI was being updated in the progresschanged event, which executes on the thread which created the background worker, therefore there shouldn't be an issue regarding threading. See https://msdn.microsoft.com/en-us/library/ka89zff4(v=vs.110).aspx for more info

rs232 communication C# data read issue

I have a problem regarding the rs232 communication with a Melfa rv-2aj robot. I am sending to commands in ASCII and when the robot replies via rs232 I get something like this: ??QY?e0?L???0???0???. My first thought was that I am not doing a proper conversion from ASCII when I read from RS232, but if I convert this set of charaters to a unicode output I get some chinesse characters and this should not be right. As the robot sends a reply via rs232, makes me think that my implementation is not wrong , but maybe my approch has some faults in it. I think "?" represent ASCII characters that are not properly displayed.
Below I have attached the source code to my application.
Can somebody give some pointers on what I doing wrong when I am reading from the serial that i get his kind of ouput?
I would really appreciate any kind of help, suggestion or reference.
Thank you very much.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace RS232_Communication
{
public partial class Form1 : Form
{
private SerialPort COM_port = new SerialPort();
private byte[] _array = new byte[] {0};
public Form1()
{
InitializeComponent();
BAUDRate.Items.Add("2400");
BAUDRate.Items.Add("4800");
BAUDRate.Items.Add("9600");
BAUDRate.Items.Add("14400");
BAUDRate.Items.Add("19200");
BAUDRate.Items.Add("28800");
BAUDRate.SelectedIndex = 2;
DATAUnit.Items.Add("5");
DATAUnit.Items.Add("6");
DATAUnit.Items.Add("7");
DATAUnit.Items.Add("8");
DATAUnit.Items.Add("9");
DATAUnit.SelectedIndex = 3;
ParityUnit.Items.Add("None");
ParityUnit.Items.Add("Odd");
ParityUnit.Items.Add("Even");
ParityUnit.Items.Add("Mark");
ParityUnit.Items.Add("Space");
ParityUnit.SelectedIndex = 2;
STOPUnit.Items.Add("One");
STOPUnit.Items.Add("Two");
STOPUnit.SelectedIndex = 1;
this.Load += new EventHandler(Form1_Load);
SendText.KeyPress +=new KeyPressEventHandler(SendText_KeyPress);
COM_port.DataReceived +=new SerialDataReceivedEventHandler(COM_port_DataReceived);
}
private string GetString(byte[] bBuffer, int iIndex, int iLen, bool bUni)
{
string sBuffer;
if (bUni) sBuffer = Encoding.Unicode.GetString(bBuffer, iIndex, iLen);
else sBuffer = Encoding.ASCII.GetString(bBuffer, iIndex, iLen);
//return the string
return sBuffer;
}
void COM_port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReceiveText.Invoke(new EventHandler(delegate
{
byte[] data = new Byte[COM_port.BytesToRead];
COM_port.Read(data, 0, data.Length);
//string read = GetString(data, 0, data.Length, true);
string read = System.Text.Encoding.ASCII.GetString(data);
ReceiveText.AppendText(read);
//ReceiveText.AppendText(COM_port.ReadExisting());
}
)
)
;
}
void Form1_Load(Object sender, EventArgs e)
{
foreach (string COMstr in SerialPort.GetPortNames())
COMPort.Items.Add(COMstr);
if (COMPort.Items.Count > 0)
COMPort.SelectedIndex = 0;
else MessageBox.Show("No COM Ports available");
}
private void ConnectBTN_Click(object sender, EventArgs e)
{
try
{
if (COM_port.IsOpen)
{
COMPort.Enabled = true;
BAUDRate.Enabled = true;
ParityUnit.Enabled = true;
STOPUnit.Enabled = true;
DATAUnit.Enabled = true;
COM_port.DtrEnable = false;
COM_port.RtsEnable = false;
ConnectBTN.Text = "Connect";
COM_port.Close();
}
else
{
COM_port.BaudRate = int.Parse(BAUDRate.Text);
COM_port.Parity = (Parity)Enum.Parse(typeof(Parity), ParityUnit.Text);
COM_port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), STOPUnit.Text);
COM_port.DataBits = int.Parse(DATAUnit.Text);
COM_port.PortName = COMPort.Text;
//COM_port.DtrEnable = true;
//COM_port.RtsEnable = true;
COM_port.Open();
COM_port.ReadTimeout = 2000;
COM_port.WriteTimeout = 2000;
COMPort.Enabled = false;
BAUDRate.Enabled = false;
ParityUnit.Enabled = false;
STOPUnit.Enabled = false;
DATAUnit.Enabled = false;
ConnectBTN.Text = "Disconnect";
}
}
catch
{
MessageBox.Show("Connection Error");
}
}
public void WriteBytes(byte[] array)
{
COM_port.Write(array, 0, array.Length);
}
public void WriteBytes(byte[] array, int index, int length)
{
COM_port.Write(array, index, length);
}
public void WriteLine(String line)
{
//string s="";
//foreach (byte b in StringToBytes(line + "\r\n"))
// s = s + b.ToString();
//COM_port.WriteLine(s);
WriteBytes(StringToBytes(line + "\r\n"));//CR + LF
}
public static byte[] StringToBytes(string input)
{
return Encoding.ASCII.GetBytes(input);
}
private void SendBTN_Click(object sender, EventArgs e)
{
if (SendText.Text != "")
{
WriteLine(SendText.Text);
//COM_port.WriteLine(SendText.Text);
SendText.Text = "";
}
}
void SendText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
WriteLine(SendText.Text);
//COM_port.WriteLine(SendText.Text);
SendText.Text = "";
}
}
}
}
I managed to figure out what was the problem. In the manual for the rv-2aj it is specified that in order to use the rs232 communication the following parameters have to be set: baud rate 9600, parity even, stop bits 2, data bits 8. So I configured my communication this way, and when I sent data to the controller I would receive strange messages as I showed in my previous post. It seems that the configuration for communication on the robot side was different then mine, so I changed the value for parity to none and the stop bits to one and now everything works as expected. I get proper feedback from the robot and the commands work. The code I wrote in c# works fine, no necessary modifications required.

NAudio Record buffer full after 5 seconds of recording

I'm making a program using Visual C# Studio that records from a microphone.
I wish to record for a few minutes, but when I try to record, it shows me an error with 'Buffer Full' after it records for 5 seconds.
This is the code I'm using:
private void button2_Click(object sender, EventArgs e) //Play Button
{
fileName = "lastReplay.wav";
FileStream FS_Write = File.OpenWrite("lastReplay.wav");
FS_Write.Close();
int deviceNumber = sourceList.SelectedItems[0].Index;
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.DeviceNumber = deviceNumber;
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100,
NAudio.Wave.WaveIn.GetCapabilities(deviceNumber).Channels);
NAudio.Wave.WaveInProvider waveIn = new
NAudio.Wave.WaveInProvider(sourceStream);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>
(sourceStream_DataAvailable);
waveWriter = new NAudio.Wave.WaveFileWriter(fileName, sourceStream.WaveFormat);
sourceStream.StartRecording();
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (waveWriter == null) return;
waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
}
Does anyone knows what is the problem?
Thanks.
There's a bunch of code in there you don't need. Get rid of creating the empty WAV file. Also, there is no need for the WaveInProvider. In fact, that is what is causing the buffer full exception, since nothing is reading from it.

Categories