webcam Afroge unhandled exception: Afroge.Video.DirectShow - c#

i am working to make a c# program that can start streaming webcam, close and capture the still image when closing.
the programs work as excepted on my development machine but when i open it on other it dosent work and gives me unhandled exception: Afroge.Video.DirectShow error.
I have added references AFroge.Video.dll and AFroge.Video.DirectShow.dll
here is the exe file and code of my project.
sendspace .com/file/4okqsi
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;
//Create using directives for easier access of AForge library's methods
using AForge.Video;
using AForge.Video.DirectShow;
namespace aforgeWebcamTutorial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Create webcam object
VideoCaptureDevice videoSource;
private void Form1_Load(object sender, EventArgs e)
{
}
void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
//Cast the frame as Bitmap object and don't forget to use ".Clone()" otherwise
//you'll probably get access violation exceptions
pictureBoxVideo.BackgroundImage = (Bitmap)eventArgs.Frame.Clone();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
//Stop and free the webcam object if application is closing
if (videoSource != null && videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
try {
if (videoSource.IsRunning)
{
videoSource.Stop();
pictureBoxVideo.BackgroundImage.Save("abc.png");
pictureBoxVideo.BackgroundImage = null;
}
}
catch (Exception er) { }
}
private void button2_Click(object sender, EventArgs e)
{
try {
//List all available video sources. (That can be webcams as well as tv cards, etc)
FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice);
//Check if atleast one video source is available
if (videosources != null)
{
//For example use first video device. You may check if this is your webcam.
videoSource = new VideoCaptureDevice(videosources[0].MonikerString);
try
{
//Check if the video device provides a list of supported resolutions
if (videoSource.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)
{
if (videoSource.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = videoSource.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
//Set the highest resolution as active
videoSource.VideoResolution = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(';')[1])];
}
}
catch { }
//Create NewFrame event handler
//(This one triggers every time a new frame/image is captured
videoSource.NewFrame += new AForge.Video.NewFrameEventHandler(videoSource_NewFrame);
//Start recording
videoSource.Start();
}
}
catch (Exception er) { }
}
}
}

Try this link!
It worked for me!
If some parts cannot be installed. Delete all of the assemblies of AForge.Net and follow following tutorial.
https://premsivakumar.wordpress.com/2010/06/28/aforge-net-visual-studio-2010-setup-tutorial/

Related

SpeechRecognitionEngine seems to be getting no audio inpit

I am trying to use SpeechRecognitionEngine in a C# application under Windows 11
I have tried the default microphone array that works with Cortana. I have tried an USB microphone and a bluetooth one. They all show they are working in Settings->Sound
I cannot get any of the events to fire including SpeechDetected and AudioStateChanged
Here is my code based on the Microsoft example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;
using System.Diagnostics;
namespace Speech_Test
{
public partial class Form1 : Form
{
SpeechRecognitionEngine recognizer = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-GB"));
Choices services = new Choices(new string[] { "restaurants", "hotels", "gas stations" });
Choices cities = new Choices(new string[] { "Seattle", "Boston", "Dallas" });
GrammarBuilder findServices = new GrammarBuilder("Find");
findServices.Append(services);
findServices.Append("near");
findServices.Append(cities);
Grammar servicesGrammar = new Grammar(findServices);
recognizer.LoadGrammarAsync(servicesGrammar);
recognizer.SpeechDetected +=
new EventHandler<SpeechDetectedEventArgs>(recognizer_SpeechDetected);
recognizer.AudioStateChanged +=
new EventHandler<AudioStateChangedEventArgs>(recognizer_AudioStateChanged);
// Add a handler for the speech recognized event.
recognizer.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.SpeechRecognitionRejected +=
new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRejected);
// Configure the input to the speech recognizer.
recognizer.SetInputToDefaultAudioDevice();
recognizer.RecognizeAsync(RecognizeMode.Multiple);
//recognizer.EmulateRecognize("Find restaurants near Dallas");
}
catch (Exception ex)
{
Debug.WriteLine(ex.InnerException.Message);
}
}
// Handle the AudioStateChanged event.
private void recognizer_AudioStateChanged(object sender, AudioStateChangedEventArgs e)
{
Debug.WriteLine("The new audio state is: " + e.AudioState);
}
private void recognizer_SpeechDetected(object sender, SpeechDetectedEventArgs e)
{
Console.WriteLine(" Speech detected at AudioPosition = {0}", e.AudioPosition);
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Debug.WriteLine("Recognized text: " + e.Result.Text);
}
private void recognizer_SpeechRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
Debug.WriteLine("Rejected text: " + e.Result.Text);
}
}
}
Any suggestions on how to find out why audio is not getting through?
Thanks

Get connection status VPN using dotras

I write code to create and connect to VPN using Dotras in C#. It works very good, but when I write code to get connection status, It doesn't work.
I read Dotras document, and write code like example, but It still doesn't work.
It doesn't show status in multiple line textbox. :(
Please show me, what I wrong. Thank you.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DotRas;
using System.Net;
namespace VPN1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_create_vpn_Click(object sender, EventArgs e)
{
try
{
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private RasHandle handle = null;
private void btn_dial_Click(object sender, EventArgs e)
{
this.rasDialer1.EntryName = txt_vpn_user.Text;
string username = txt_user.Text;
string password = txt_pass.Text;
this.rasDialer1.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.rasDialer1.Credentials = new NetworkCredential(username, password);
this.handle = this.rasDialer1.DialAsync();
this.btn_disconnect.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void rasDialer1_StateChanged(object sender, StateChangedEventArgs e)
{
this.txt_status.AppendText(e.State.ToString() + "\r\n");
}
private void rasDialer1_DialCompleted(object sender, DialCompletedEventArgs e)
{
if(e.Cancelled)
{
this.txt_status.AppendText("Cancelled");
}
else if(e.TimedOut)
{
this.txt_status.AppendText("Timeout");
}
else if(e.Connected)
{
this.txt_status.AppendText("Connection successful");
}
else if (e.Error != null)
{
this.txt_status.AppendText(e.Error.ToString());
}
if(!e.Connected)
{
this.btn_disconnect.Enabled = false;
}
}
private void btn_disconnect_Click(object sender, EventArgs e)
{
if(this.rasDialer1.IsBusy)
{
this.rasDialer1.DialAsyncCancel();
}
else
{
RasConnection connection = RasConnection.GetActiveConnectionByHandle(this.handle);
if(connection!=null)
{
connection.HangUp();
}
}
}
}
}
If the events are not firing, the issue might be that the Events are not set in the events section in the properties window of the rasDialer1 control you added to the form (Form1). Using Visual Studio, Enter the design view, click on the rasDialer1 control which reveals the properties of the RasDialer you added, then navigate to events section (marked with a lightening icon) and then set the StateChanged and DialCompleted events.
OR
You can do all this from code simply by
rasDialer.StateChanged += rasDialer1_StateChanged;
rasDialer.DialCompleted += rasDialer1_DialCompleted;
somewhere in the Form1() constructor, where rasDialer1_StateChanged and rasDialer1_DialCompleted are the event handlers in your code.
I'm also anticipating a potential error within your code where accessing UI controls in those event handlers will get you a Cross-thread operation not valid error since they are called from an async operation this.rasDialer1.DialAsync();
The right way of accessing controls from methods called from another thread is below ...
textbox1.Invoke(new Action(() => textbox1.text = "my string"));
Try using dial instead of dialAsync
try:
{
File.WriteAllText("your rasphone.pbk path","")//Add
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}

Can't control arduino analog read via Visual Studio GUI

I'm trying to make GUI for my arduino analogread. The GUI display graph and text line of the value that arduino read. I'm using zedgraph for graphing.
I need to write "on" in the serial monitor window of arduino to start the readings. it runs well. But when I try to control via GUI I made with C# Visual
Studio, the reading won't start. it says "Access to the port 'COM3' is denied".
Here's my arduino code:
void loop() {
while (Serial.available() > 0)
{
input += (char) Serial.read(); // Read in one char at a time
delay(5);
} if (input == "on")
{
myservo.write(0);
---analog reading and Serial.println arduino---
} if (input == "off")
{
myservo.write(115);
}
}
And this is my visual studio code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZedGraph;
using System.IO.Ports;
using System.Globalization;
namespace concentrationMeasurement
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = port_name.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open();
myport.WriteLine("on");
data_tb.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"Error");
}
}
private void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
data_tb.AppendText(time + "\t\t" + in_data + "\n");
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void save_btn_Click(object sender, EventArgs e)
{
try{
string pathfile = #"C:\Users\ajis.aprl\Documents\TA bgt\data_GUI\";
string filename = "concentration.txt";
System.IO.File.WriteAllText(pathfile + filename, data_tb.Text);
MessageBox.Show("Data has been saved to "+pathfile,"Save File");
}
catch (Exception ex3){
MessageBox.Show(ex3.Message, "Error");
}
}
private void Form1_Load(object sender, EventArgs e)
{
plotGraph();
SetSize();
}
private void plotGraph()
{
GraphPane myPane = zedGraphControl1.GraphPane;
myPane.Title.Text = "Concentration Growth";
myPane.XAxis.Title.Text = "time";
myPane.YAxis.Title.Text = "concentration";
}
}
}
So I got 2 problem here:
As I said, I can't run my analog reading via GUI, it says "Access to the port 'COM3' is denied".
in myPane.Title.Text, myPane.XAxis.Title.Tex, and myPane.YAxis.Title.Text, there's error in "Text" it says:
"Error 3 'string' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)"
I googled everywhere but I can't find the answer. Please if anyone know what I'm missing. Can you tell me what's wrong with my code/logic? Thank you.

Use values recieved from serial port

I'm trying to make a little weather station that recieves 4 values.
This is the data I get when reading from the serial port:
And I already managed to split it,so I only get the values.
This looks like this:
Now I'ld like to do something with those values (Putting them in graphs, save as CSV, Add comma for temperature, go from hexadecimal to decimal for the pressure,.. ) but I have no idea how I can work with them.
I Was thinking of putting them in an array (undifined rows x 4 columns) or list, but I've no idea how to do that.
Or maybe there is an eaier solution that I have not thinked about.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace WeatherStation
{
public partial class Form1 : Form
{
private SerialPort port;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
try
{
port = new SerialPort("COM3", 9600, Parity.None, 8);
port.DataReceived += DataReceivedHandler;
port.Open();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadLine();
string[] ret = data.Split(':');
if (data != String.Empty)
{
Invoke(new Action(() => txtBoxData.AppendText(ret[1] + '\t')))
}
}
catch (Exception exc) //!!
{
MessageBox.Show(exc.Message);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
port.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBoxData.Clear();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
StreamWriter writer = new StreamWriter(#"test.cvs");
writer.Write(txtBoxData.Text);
writer.Close();
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
}
}
Thanks in advance for your help
You could store the tag, value, and timestamp as a row in a file. Comma-delimited would probably work.
if (data != String.Empty)
{
string[] ret = data.Split(':');
string text = string.Format("{0:yyyy-MM-dd HH:mm:ss},{1},{2}", DateTime.Now, ret[0], ret[1]);
File.AppendAllText(#"c:\MyFile.csv", text);
}
The above code will add one line per event, to a file named "MyFile.csv". The first column will have the date and time, the second will have the metric type, and the third will have the value.
Once you have added enough lines to the file, you can open it in Excel and make it into a useful table by using the pivot table feature, then create a graph of the data. Or you could load the data into a database and run queries against it.

'Emgu.CV.Invoke' threw an exception

I am relativity new EmguCV but I have done a lot of research and read a few tutorials and look through this site for the answer. All of the other people with similar problems are told to add the unmangaged dll to the output folder. I have done this and I am still getting this error 'Emgu.CV.Invoke' threw an exception.
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.VFW;
using System.Drawing.Imaging;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class SandBox : Form
{
private bool DeviceExist = false;
public VideoCaptureDevice FinalVideoSource;
public FilterInfoCollection VideoCaptureDevices;
private Capture capture;
private VideoWriter captureOutput;
private void FinalVideoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgseventArgs)
{
Bitmap image = (Bitmap)eventArgs.Frame.Clone();
image.RotateFlip(RotateFlipType.Rotate180FlipY);
pictureBox1.Image = image;
}
public SandBox()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = " ";
FPS.Text = " ";
try
{
VideoCaptureDevices = new FilterInfoCollection(AForge.Video.DirectShow.FilterCategory.VideoInputDevice);
DeviceExist = true;
foreach (AForge.Video.DirectShow.FilterInfo VideoCaptureDevice in VideoCaptureDevices)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No device on your system");
}
}
private void Start_Click(object sender, EventArgs e)
{
FinalVideoSource = new VideoCaptureDevice(VideoCaptureDevices[comboBox1.SelectedIndex].MonikerString);
FinalVideoSource.NewFrame += new NewFrameEventHandler(FinalVideoSource_NewFrame);
FinalVideoSource.Start();
label1.Text = "Device running...";
Start.Enabled = false;
Stop.Enabled = true;
timer1.Enabled = true;
capture = new Capture();
captureOutput = new VideoWriter("test.avi", 30, 1280, 720, true);
Image<Bgr, Byte> ImageFrame = capture.QueryFrame();
captureOutput.WriteFrame(ImageFrame);
}
}
The error is being thrown in line capture = new Capture();. I cant figure out what is wrong with the project. Just to clarify I am only using EmguCV to record video not to display it on screen. Any help would be greatly appreciated.
The type initializer for 'Emgu.CV.CvInvoke' threw an exception its means that EMGU.CV file is not dectecting by code. this is due to system dependency. you need to go in to configration manger window in visual stdio and choose your required platform and then copy respective dll files(64 dll files forx64 and 32bit dll for x86 can be downloaded from emgu website ) according to your platform. copile it now there is no error like emgu.cv.invoke
http://www.emgu.com/wiki/index.php/Setting_up_EMGU_C_Sharp

Categories

Resources