I was going to make a forms application in C# that recognize a voice and then the user could say some simple commands like "hi" and the computer would respond with "hi there, can I help you with someting". I am 100% sure that my mic works but when I debugg the program it seems like it does not recognize any commands or audio from my microphone. I am using Visual Studio Community 2015. I was wondering, is there anything i've missed or done wrong? The computer loads up the form and talks to me but it doesn't recognize my voice. I would appreciate any help. Thanks!
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.Synthesis;
using System.Speech.Recognition;
namespace VoiceHost
{
public partial class Form1 : Form
{
SpeechSynthesizer Host = new SpeechSynthesizer();
Choices services = new Choices();
public Form1()
{
SpeechRecognitionEngine UserRecog = new SpeechRecognitionEngine();
services.Add(new string[] {"hi"});
Grammar gr = new Grammar(new GrammarBuilder(services));
Say("hello, my name is voice host, how can I help");
try
{
UserRecog.RequestRecognizerUpdate();
UserRecog.LoadGrammar(gr);
UserRecog.SpeechRecognized += UserRecog_SpeechRecognized;
UserRecog.SetInputToDefaultAudioDevice();
UserRecog.RecognizeAsync(RecognizeMode.Multiple);
}
catch { return; }
}
public void Say(string responseMessage)
{
Host.Speak(responseMessage);
}
private void UserRecog_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string userOrder = e.Result.Text;
if (userOrder == "hi")
{
Say("hi there, can I help you with someting");
}
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
catch { Exception ex }
that way you'll see if anything breaks in your code.
Related
Hello it is probably easy question for you, I'm a beginner and I'm making my own simple game and I want to use a Class:Gamer, which I want to initialize in MainWindow(Form1.cs) from a save file. From then, I want to use it on another Forms aswell, but somehow I can't make the instance go public.
Could you tell me what I'm doing wrong? Or is there another way how to solve this?
Thank you :)
Code on Form1:
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.Drawing.Text;
using System.IO;
namespace THE_GAME
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static Gamer Player;
private void MainWindow_Load(object sender, EventArgs e)
{
//load from savefile lvl;hp;money;gun;armor,name
string allData = File.ReadAllText("../../saveFile/save.txt");
string[] dataFromSave = new string[5];
dataFromSave = allData.Split(';');
Player = new Gamer(dataFromSave[0], dataFromSave[1], dataFromSave[2], dataFromSave[3], dataFromSave[4], dataFromSave[5]);
}
}
}
Code on secondForm2:
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.Drawing.Text;
namespace THE_GAME
{
public partial class Statistics : Form1
{
public Statistics()
{
InitializeComponent();
}
private void Statistics_Load(object sender, EventArgs e)
{
//labels stats
labelName.Text = Form1.Player.GetName();
labelHealth.Text = Form1.Player.GetHealth().ToString();
labelMoney.Text = Form1.Player.GetMoney().ToString();
}
private void buttonBack_Click(object sender, EventArgs e)
{
MainMenu menu = new MainMenu();
menu.Show();
this.Close();
}
}
}
Thank you for your time.
To get at the Gamers Player object from a different Form just do
Form1.Player;
ie
var nam = Form1.Player.Name;
Form1.Player.Die();
etc
PS As I said in a comment - its extremely odd to dereive a form of yours from another one of your forms. Like this
public partial class Statistics : Form1
Hello I am working on c# simple project.
This is the code:
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.Threading;
using Microsoft.Win32;
using System.IO;
private void SetStartup()
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (chkStartUp.Checked)
rk.SetValue(AppName, Application.ExecutablePath);
else
rk.DeleteValue(AppName,false);
}
namespace web1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// open browser
Thread.Sleep(6000);
System.Diagnostics.Process.Start("https://google.com/");
}
}
}
It shows errors "The name "AppName" does not exist in the current context" and "The namespace cannot contain members such as fields or methods directly"
I want to:
If I click on this program .exe, it should run on the startup (every startup).
How to deal with it? I've tried so many ideas, but doesn't helped.
Thanks in advance.
BTW: it's my first time here, nice to meet you all!
I can detect the network connection change event while running a C# code, how would I register an exe when Windows detects this event. What all details would I need. Below is how I am using this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
testing t = new testing();
Console.Read();
}
}
public class testing{
public testing()
{
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
Console.WriteLine("network is available");
}
}
}
}
What you could maybe do is in your method that is triggered to start a new process and execute your exe
I'm currently building an application for Windows Phone 8.1 using C#,
The aim of the app is to assess audio signals from the device's microphone, initially for frequency,
I was hoping to use the Accord library to help with this but have run into these errors:
XamlCompiler error WMC1006: Cannot resolve Assembly or Windows
Metadata file 'System.Windows.Forms.dll'
\Program Files
(x86)\MSBuild\Microsoft\WindowsXaml\v12.0\8.1\Microsoft.Windows.UI.Xaml.Common.targets(327,9):
Xaml Internal Error error WMC9999: Type universe cannot resolve
assembly: System.Windows.Forms, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089.
I'm fairly certain that this is arising due to the references included in the project but I'm not to sure,
Here is my current code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Accord.Audio;
using Accord.Controls;
using Accord.DirectSound;
using Accord.Imaging;
using Accord.MachineLearning;
using Accord.Math;
using Accord.Statistics;
using Accord;
using AForge;
using AForge.Controls;
using AForge.Imaging;
using AForge.Math;
using AForge.Video;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using System.Diagnostics;
using Windows.Media;
using Windows.Media.MediaProperties;
using Accord.Audio.Formats;
using Accord.Audio.Windows;
namespace Test2
{
public sealed partial class MainPage : Page
{
private MediaCapture _mediaCaptureManager;
private StorageFile _recordStorageFile;
private bool _recording;
private bool _userRequestedRaw;
private bool _rawAudioSupported;
private IRandomAccessStream _audioStream;
private FileSavePicker _fileSavePicker;
private DispatcherTimer _timer;
private TimeSpan _elapsedTime;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
InitializeAudioRecording();
}
private static void DecodeAudioFile()
{
String fileName = "record.wav";
WaveDecoder sourceDecoder = new WaveDecoder(fileName);
Signal sourceSignal = sourceDecoder.Decode();
RaisedCosineWindow window = RaisedCosineWindow.Hamming(1024);
Signal[] windows = sourceSignal.Split(window, 512);
ComplexSignal[] complex = windows.Apply(ComplexSignal.FromSignal);
complex.ForwardFourierTransform();
Debug.WriteLine(complex);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private async void InitializeAudioRecording()
{
_mediaCaptureManager = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
settings.MediaCategory = MediaCategory.Other;
settings.AudioProcessing = (_rawAudioSupported && _userRequestedRaw) ? AudioProcessing.Raw : AudioProcessing.Default;
await _mediaCaptureManager.InitializeAsync(settings);
Debug.WriteLine("Device initialised successfully");
_mediaCaptureManager.RecordLimitationExceeded += new RecordLimitationExceededEventHandler(RecordLimitationExceeded);
_mediaCaptureManager.Failed += new MediaCaptureFailedEventHandler(Failed);
}
private void Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
{
throw new NotImplementedException();
}
private void RecordLimitationExceeded(MediaCapture sender)
{
throw new NotImplementedException();
}
private async void CaptureAudio()
{
try
{
Debug.WriteLine("Starting record");
String fileName = "record.wav";
_recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Create record file successfully");
Debug.WriteLine(fileName);
MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);
Debug.WriteLine("Start Record successful");
_recording = true;
}
catch (Exception e)
{
Debug.WriteLine("Failed to capture audio");
}
DecodeAudioFile();
}
private async void StopCapture()
{
if (_recording)
{
Debug.WriteLine("Stopping recording");
await _mediaCaptureManager.StopRecordAsync();
Debug.WriteLine("Stop recording successful");
_recording = false;
}
}
private async void PlayRecordedCapture()
{
if (!_recording)
{
var stream = await _recordStorageFile.OpenAsync(FileAccessMode.Read);
Debug.WriteLine("Recording file opened");
playbackElement1.AutoPlay = true;
playbackElement1.SetSource(stream, _recordStorageFile.FileType);
playbackElement1.Play();
}
}
private void Capture_Click(object sender, RoutedEventArgs e)
{
Capture.IsEnabled = false;
Stop.IsEnabled = true;
CaptureAudio();
}
private void Stop_Click(object sender, RoutedEventArgs e)
{
Capture.IsEnabled = true;
Stop.IsEnabled = false;
StopCapture();
}
private void Playback_Click(object sender, RoutedEventArgs e)
{
PlayRecordedCapture();
}
private void backBtn_Click(object sender, RoutedEventArgs e)
{
if (Frame.CanGoBack)
{
Frame.GoBack();
}
}
}
}
Any help or guidance in resolving these errors would be greatly appreciated,
Thanks
The original Accord.NET Framework is not accessible on other platforms than .NET.
There is an effort (of which I am responsible) for porting Accord.NET to mobile platforms via Portable Class Libraries. Several of these packages have been published on NuGet as well (prefix Portable Accord).
The Audio package is not published on NuGet, but you should be able to build it from source for Windows Phone 8.1. You can find the source for Portable Accord here.
Please note that only playback is supported, recording is not.
Wondering if anyone could help with my problem. Below is the code, and after the code an explination of where the exception is thrown.
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.Web;
using WatiN.Core;
using System.Threading;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(createApplications);
Settings.AutoStartDialogWatcher = false;
t.SetApartmentState(System.Threading.ApartmentState.STA);
t.Start();
}
private void createApplications()
{
createApp("username", "password", "Test App", "This is just a test description", "http:/mysite.com");
}
private void createApp(String username, String password, String appName, String description, String appUrl) {
var currentBrowser = new IE("http://mysite.com/login/php");
currentBrowser.TextField(Find.ById("username")).TypeText(username);
currentBrowser.TextField(Find.ById("password")).TypeText(password);
currentBrowser.Button(Find.ById("submit")).Click();
currentBrowser.GoTo("http://mysite.com/createmusicapp.php");
currentBrowser.TextField(Find.ById("application_name")).TypeText(appName);
currentBrowser.TextField(Find.ById("application_description")).TypeText(description);
currentBrowser.TextField(Find.ById("application_url")).TypeText(appUrl);
currentBrowser.RadioButton(Find.ById("client_application_desktop_1")).Click();
currentBrowser.RadioButton(Find.ById("client_application_is_writable_1")).Click();
WatiN.Core.Image captchaImage = currentBrowser.Div(Find.ById("recaptcha_image")).Image(Find.ByStyle("display", "block"));
Form2 captcha = new Form2(captchaImage.Src);
captcha.ShowDialog();
}
}
}
The exception is thrown on this line:
currentBrowser.TextField(Find.ById("username")).TypeText(username);
BUT, it's thrown when it gets to this line:
captcha.ShowDialog();
It logs in, and fills in the app details and Form2 loads fine, but once loaded, after around 2-3 seconds the exception happens. I am wondering if it's anything to do with the threads? But I wouldn't know how to solve it if it was.
The complete exception thrown is:
The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))
Got! Because of your thread, in windows development, microsoft doesn't suggest access UI by thread. If you really need, use mutex to avoid two or more threads accessing the same UI elemnt at the same time.