So I am trying to change a voice in C# for the System.Speech.Synthesis library. It will work for me when I attempt the code in console mode. However when I am working on a windows application it does not change the voice while giving no errors. Here is the code of the windows application that works asside from the voice change.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
namespace JarvisRev1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.button1.Click += new EventHandler(button1_Click);
this.button2.Click += new EventHandler(button2_Click);
this.button3.Click += new EventHandler(button3_Click);
foreach (InstalledVoice voice in sSynth.GetInstalledVoices())
{
cbVoice.Items.Add(voice.VoiceInfo.Name);
}
}
SpeechSynthesizer sSynth = new SpeechSynthesizer();
PromptBuilder pBuilder = new PromptBuilder();
SpeechRecognitionEngine sRecognize = new SpeechRecognitionEngine();
private void button1_Click(object sender, EventArgs e)
{
pBuilder.ClearContent();
pBuilder.AppendText(textBox1.Text);
sSynth.SelectVoice("IVONA 2 Brian");
sSynth.SpeakAsync(pBuilder);
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
button3.Enabled = true;
Choices sList = new Choices();
sList.Add(new string[] { "hello", "test", "it works", "how", "are", "you", "today", "i", "am", "fine", "exit", "close", "quit", "so", "hello how are you" });
Grammar gr = new Grammar(new GrammarBuilder(sList));
try
{
sRecognize.RequestRecognizerUpdate();
sRecognize.LoadGrammar(gr);
sRecognize.SpeechRecognized += sRecognize_SpeechRecognized;
sRecognize.SetInputToDefaultAudioDevice();
sRecognize.RecognizeAsync(RecognizeMode.Multiple);
sRecognize.Recognize();
}
catch
{
return;
}
}
private void button3_Click(object sender, EventArgs e)
{
sRecognize.RecognizeAsyncStop();
button2.Enabled = true;
button3.Enabled = false;
}
private void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result.Text == "exit")
{
Application.Exit();
}
else
{
textBox1.Text = textBox1.Text + " " + e.Result.Text.ToString();
}
}
}
}
This is the code in console mode that is working for me.
using System;
using System.Speech.Synthesis; // Add reference to System.Speech
class Program
{
static void Main(string[] args)
{
var synth = new SpeechSynthesizer();
synth.SelectVoice("IVONA 2 Brian");
synth.SpeakAsync("For you Sir, Always.");
foreach (var voice in synth.GetInstalledVoices())
{
Console.WriteLine(voice.VoiceInfo.Name);
}
Console.ReadLine();
}
}
Have same issue when Microsoft Irina Desktop voice is available in system. Workaround to set voice explicitly in prompt, e.g.:
using System.Speech.Synthesis;
var synth=new SpeechSynthesizer();
var builder=new PromptBuilder();
builder.StartVoice("Microsoft David Desktop");
builder.AppendText("Hello, World!");
builder.EndVoice();
synth.SpeakAsync(new Prompt(builder));
As you already utilize PromptBuilder, try to add StartVoice and EndVoice calls around text.
Related
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
Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.
I am at a loss after looking at relevant posts and documentation, many others seem to have had similar problems, but none of the existing solutions results in any keypresses actually being recognized by the browser.
All my code is below, just an empty form trying to type in a username/password on a website that currently doesn't have an API but it is coming. So this is just a bandaid fix until their API is fleshed out. Mostly just need to login and send keypresses to the website, but nothing seems to be working.
I have also tried: https://ourcodeworld.com/articles/read/520/simulating-keypress-in-the-right-way-using-inputsimulator-with-csharp-in-winforms
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 CefSharp;
using CefSharp.WinForms;
namespace Hydros_tmp_api
{
public partial class Form1 : Form
{
public ChromiumWebBrowser chromeBrowser;
string CurrentAddress = "";
public void InitializeChromium()
{
CefSettings settings = new CefSettings();
// Initialize cef with the provided settings
Cef.Initialize(settings);
// Create a browser component
chromeBrowser = new ChromiumWebBrowser("https://www.coralvuehydros.com/app/#/status");
// Add it to the form and fill it to the form window.
Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
(chromeBrowser).LoadingStateChanged += Browser_FrameLoadEnd;
chromeBrowser.AddressChanged += Browser_AddressChanged;
}
public Form1()
{
InitializeComponent();
InitializeChromium();
}
private void Form1_Load(object sender, EventArgs e)
{
}
async void Browser_FrameLoadEnd(object sender, LoadingStateChangedEventArgs e)
{ // Jumps in here when the page is fully loaded:
if (e.IsLoading == false)
{
if (CurrentAddress.Contains("login"))
{
timer_login.Enabled = true;
}
}
}
private void Browser_AddressChanged(object sender, AddressChangedEventArgs e)
{
CurrentAddress = e.Address;
}
private void timer_login_Tick(object sender, EventArgs e)
{
timer_login.Enabled = false;
chromeBrowser.GetBrowserHost().SetFocus(true);
Random rnd = new Random();
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.Tab, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyDown
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.Tab, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyUp
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.T, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyDown
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.T, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyUp
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
}
}
}
Edit: It appears to be a specific oddity with their website that is not accepting simulated input because it works fine on other sites? So idk where to go from here.
Im trying to build a voice recognition program based on this link :
https://www.youtube.com/watch?v=OJdVfwiTIXE
The problem is..When I run the windows form after compiling, it is not recognizing and responding to my voice commands...I am using .NET framework 4 client profile for this project. I made reference only to "system.speech" and Im using the build in microphone of my laptop for voice input..
Here is my text file(i wrote it line by line from the first line):
hi
hello henry
close
close henry
Here is my code so far :
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.Speech.Recognition;
using System.Speech.Synthesis;
using System.IO;
namespace Henry
{
public partial class Form1 : Form
{
SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
SpeechSynthesizer Henry = new SpeechSynthesizer();
Random rnd = new Random();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_recognizer.SetInputToDefaultAudioDevice();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(#"C:\Henry\com.txt")))));
_recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recognizer_SpeechRecognized);
_recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
int ranNum = rnd.Next(1, 10);
string speech = e.Result.Text;
switch (speech)
{
//GREETINGS
case "hi":
case "hello henry":
if (ranNum < 6) { Henry.Speak("Hello sir"); }
else if (ranNum > 5) { Henry.Speak("Hi"); }
break;
case "close":
case "close henry":
Henry.Speak("Until next time");
Close();
break;
}
}
}
}
I am having an error with this Speech Recognition, I keep getting "At least one grammar must be loaded before doing a recognition" I can't get the images to display when you say its corresponding linked name.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SpeechLib;
using System.IO;
using System.Speech.Recognition;
using System.Globalization;
namespace SimpleSpeechRecognition
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SpeechRecognitionEngine recognizer;
private void Form1_Load(object sender, EventArgs e)
{
speechListBox1.Items.Add("Dog");
speechListBox1.Items.Add("Elephant");
speechListBox1.SpeechEnabled = true;
recognizer = new SpeechRecognitionEngine(new CultureInfo("en-GB"));
recognizer.SetInputToDefaultAudioDevice();
Choices choices = new Choices("Dog", "Elephant");
GrammarBuilder m_GrammarBuilder = new GrammarBuilder(choices);
Grammar m_Speech = new Grammar(m_GrammarBuilder);
recognizer.LoadGrammar(m_Speech);
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
foreach (RecognizedWordUnit word in e.Result.Words)
{
switch (word.Text)
{
case "Dog":
pictureBox1.Image = Image.FromFile("C:\\" + "dog.jpg");;
break;
case "Elephant":
pictureBox1.Image = Image.FromFile("C:\\" + "elephant.jpg");
break;
}
}
}
private void speechListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//MessageBox.Show(speechListBox1.SelectedItems[0].ToString());
SayPhrase(speechListBox1.SelectedItems[0].ToString());
//pictureBox1.Image = Image.FromFile("C:\\" + "dog.jpg");
//pictureBox1.Image = Image.FromFile(((FileInfo)speechListBox1.SelectedItem).FullName);
pictureBox1.Refresh();
}
private void SayPhrase(string PhraseToSay )
{
SpeechVoiceSpeakFlags SpFlags = new SpeechVoiceSpeakFlags();
SpVoice Voice = new SpVoice();
Voice.Speak(PhraseToSay, SpFlags);
}
}
}
The errors self-explanatory:
The speech engine must have a collection of 'Choices' to listen out for, however these need to be built into appropriate Grammar for the speech engine to listen out for.
GrammarBuilder m_GrammarBuilder = new GrammarBuilder(choices);
Grammar m_Speech = (m_GrammarBuilder);
Then just load the grammar in:
recognizer.LoadGrammar(m_Speech);
I think that should solve your problem. It also worth noting that you can unload and load different sets of grammar via the .UnloadGrammar() function as well.
Additionally, it's also worth initializing a SpeechRecognitionEngine with an appropriate culture info. For English (UK) this is:
new SpeechRecognitionEngine(new CultureInfo("en-GB"))