Speech in using System.Speech.Synthesis is not recognized. - c#

I'm trying to use the Speech Synthesis function for an universal app.
I looked at the Microsoft documentation and its says that the name space is System.Speech.Synthesis.
However, when i type System.Speech.Synthesis. It says that speech is not recognized.
What am i doing wrong?

Here is a working example:
using System.Speech.Synthesis;
static void Main(string[] args)
{
...
// Speech helper
SpeechSynthesizer reader = new SpeechSynthesizer();
const string msg = "Hello";
Console.WriteLine(msg);
reader.SpeakAsync(msg);
}
Also, make sure you referencing 'System.Speech':

You need to add the reference to your project. References, right click, add reference after finding it.
If that still doesn't work you need to right click in your .cs file on your variable and resolve to System.Speech.

Related

NullReferenceException while creating a SpeechRecognitionEngine object

I'm currently trying to implement some speech recognition in one of my c# project, and so I found this library :
https://learn.microsoft.com/en-us/dotnet/api/system.speech.recognition.speechrecognitionengine?view=netframework-4.8
Providing this code as an example :
using System;
using System.Speech.Recognition;
namespace SpeechRecognitionApp
{
class Program
{
static void Main(string[] args)
{
// Create an in-process speech recognizer for the en-US locale.
using (
SpeechRecognitionEngine recognizer =
new SpeechRecognitionEngine(
new System.Globalization.CultureInfo("en-US")))
{
// Create and load a dictation grammar.
recognizer.LoadGrammar(new DictationGrammar());
// Add a handler for the speech recognized event.
recognizer.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
// Configure input to the speech recognizer.
recognizer.SetInputToDefaultAudioDevice();
// Start asynchronous, continuous speech recognition.
recognizer.RecognizeAsync(RecognizeMode.Multiple);
// Keep the console window open.
while (true)
{
Console.ReadLine();
}
}
}
// Handle the SpeechRecognized event.
static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Console.WriteLine("Recognized text: " + e.Result.Text);
}
}
}
Which should do exactly what I need.
So I created a new project in Visual Studio, copy-pasted the code, and run it.
There is no compilation error, but the constructor of SpeechRecognitionEngine, taking a non-null CultureInfo object as an argument, throws a System.NullReferenceException in System.Speech.dll.
To try to debug this, I made sure
new System.Globalization.CultureInfo("en-US")
returns a non-null object, and that this culture was installed.
I also updated my framework to 4.8, and run the project both as administrator and normal user.
I'm also using a x64 CPU platform, as the build fails with an ANY CPU platform.
It seems to me like I misconfigured something somewhere, as the code itself shouldn't be wrong.
Do you have any idea how to solve my problem ?
Thank you for your help.
EDIT : this may be linked to this problem, though I don't know if it's of any help :
NullReferenceException when starting recognizer with RecognizeAsync
I had the same error, but found the issue on my end. If you have the same issue as me, it may be that your project is using System.Speech.dll from an older framework, which I believe was causing my error. Or it may have been incompatibility between my target framework the dll?
I used NuGet to add System.Speech by Microsoft to my project. It added System.Speech (6.0.0) to the project references. This removed the null exception I was getting.
For information only, I initially added a reference to v3.0 framework, and that was causing my issue.

Add XML reference to a single c# script in visual studio

This may be a stupid question but how can I add XML references in Visual Studio to a single c# file?
I want to use using System.xml;, but Visual Studio is not able to find it. After a little research, I found out that I have to reference the DLL. But I only created a single C# script and no project: the project window on the right side is empty (shows 0 projects) and, when I right-click on it, there is no option for adding a reference.
The script should provide a few functions for reading specific XML files and basically should be a plug-in which can be implemented in any C# program if needed - so I think I don't really want to make an application out of it.
You can use the following code to add xml reference to c# script and call the script successfully.
static void Main(string[] args)
{
string code = File.ReadAllText("D:\\Code.cs");
CSScript.Evaluator.ReferenceAssembliesFromCode(code);
dynamic block = CSScript.Evaluator.LoadCode(code);
block.ExecuteAFunction();
Console.ReadKey();
}
Code.cs
using System;
using System.Xml;
class MyScript
{
public void ExecuteAFunction()
{
string path = "D:\\t.xml";
XmlDocument document = new XmlDocument();
document.Load(path);
Console.WriteLine(document.LastChild.InnerXml);
Console.ReadKey();
}
}
Besides, you also look at How to Add a Reference to a C# Script.

.NET client library for Watson Assistant what is an _assistant object?

I am trying to communicate with my chatbot via a Windows Form App (using C#). I have installed the SDK into Visual Studio, but I am having trouble using it. I have read through all the documentation, including on GitHub, however, because this is my first time using the SDK, I am quite confused about how to get it to work. At this point, I simply want to be able to send a "Message" and read the chatbot's response.
Which namespaces do I have to include (i.e. "using IBM.Watson...")? Because I have tried authenticating but am getting the error: "namespace AssistantService could not be found", as per the IAM authentication in dotnet guide on GitHub. Also, what is an "_assistant" object and how to I create one, the docs don't explain this so I keep getting the error "_assistant does not exist in the current context..."
This is the link that to the SDK I am following: https://github.com/watson-developer-cloud/dotnet-standard-sdk
I am trying to authenticate with the instructions at that link but am not succeeding. I am trying to use these instructions to call the Watson Assistant: https://github.com/watson-developer-cloud/dotnet-standard-sdk/tree/development/src/IBM.WatsonDeveloperCloud.Assistant.v1
****************UPDATE*****************
using System.Windows.Forms;
using IBM.WatsonDeveloperCloud.Assistant.v1.Model;
using IBM.WatsonDeveloperCloud.Assistant.v1;
using IBM.WatsonDeveloperCloud.Util;
namespace Watson_Assistant_Test
{
public partial class Form1 : Form
{
AssistantService _assistant;
string[] _questionArray = { "Hello there" };
public Form1()
{
TokenOptions iamAssistantTokenOptions = new TokenOptions()
{
IamApiKey = "Y....H",
IamUrl = "https://gateway-syd.watsonplatform.net/assistant/api"
};
_assistant = new AssistantService(iamAssistantTokenOptions, "2018-07-10");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageRequest messageRequest = new MessageRequest()
{
Input = new InputData()
{
Text = _questionArray[0]
}
};
var result = _assistant.Message("d...5", messageRequest);
label1.Text = result.ResponseJson.ToString();
}
}
}
I think I am still not creating the AssistantObject correctly. I am getting this error: ServiceResponseException: The API query failed with status code NotFound: Not Found.
Thanks, Harry
[I am not a C# developer and have not used that SDK, but... :)]
There is a small sample as part of the SDK that works with the car dashboard example. Because of the renaming of Watson Conversation to Watson Assistant it is still using the old object names (both work).
The code uses this namespace:
using IBM.WatsonDeveloperCloud.Assistant.v1.Model
Based on the code itself it checks for the following parts of TokenOptions:
IamApiKey
IamAccessToken
ServiceUrl
My guess is that you have to rename IamUrl to ServiceUrl in your code.

Reference to the right "System" in c# project

I am new to c# and visual studio and have run into some trouble.
I have created a project with references to "Windows" and ".Net" in visual studio because I want to test a little with smart cards.
The code:
using System;
using Windows.Devices.Enumeration;
using Windows.Devices.SmartCards;
class HandleSmartCard
{
public async void checkNumberOfSmartCards()
{
string selector = SmartCardReader.GetDeviceSelector();
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
// return "2";
}
}
So far it looks fine. However I also want the project to be able to use
System.Windows.Forms; which I have used in a previos test.
I add reference to System.Windows.Forms; and try to create a form. However in that form when I try this:
Form prompt = new Form();
System.Windows.Forms.Button confirmation = new System.Windows.Forms.Button() { Dock = DockStyle.Bottom };
confirmation.Click += (sender, e) => { prompt.Close(); };
I get a red line under "Close" with the message:
Reference to type component claims it is defined in system but could
not be found.
System is referenced at top of file, but I am guessing it is the wrong type of system right?
Can I somehow use "both Systems" in one project so to speak?
I hope someone understands what I mean and can help me understand this.
You're most likely working on a UWP app. The API for UWP apps is a very small subset of the full .NET framework. You can find more information here
https://msdn.microsoft.com/en-us/library/windows/apps/mt185501.aspx
You're attempting to reference System.Windows.Forms which is not allowed in UWP applications.
Looks like you're trying to create a popup to ask the user something. For this, use the MessageDialog class.
https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.popups.messagedialog.aspx

Windows.UI.Notifications is missing

I want to create simple toast notification to action center in windows 10 from this example. But I got problem on Step 2:
using Windows.UI.Notifications;
It`s missing. But I have spent a lot of time to find it and got no result. I really have no idea where I can find or at least download it.
What I tried:
After long search I found Windows.UI.dll in C:\Windows\System32 but when I try to add it as reference into project I got this error. Even after I tried to copy it and made this fully accessible nothing changed
I tried to reinstall .Net (I`m using 4.5.2)
Installed Windows 10 SDK
Tried to import with global
Added
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
Added System.Runtime.dll reference
Example code which probably is useless for you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.QueryStringDotNET;
using Windows.UI.Notifications;
namespace MessagerClient.Notifications {
class DefaultWindowsNotification {
public static void notificationTest() {
string title = "Andrew sent you a picture";
string content = "Check this out, Happy Canyon in Utah!";
string image = "http://blogs.msdn.com/something.jpg";
string logo = "ms-appdata:///local/Andrew.jpg";
ToastVisual visual = new ToastVisual() {
BindingGeneric = new ToastBindingGeneric() {
Children =
{
new AdaptiveText()
{
Text = title
},
new AdaptiveText()
{
Text = content
},
new AdaptiveImage()
{
Source = image
}
},
AppLogoOverride = new ToastGenericAppLogo() {
Source = logo,
HintCrop = ToastGenericAppLogoCrop.Circle
}
}
};
Console.WriteLine("NOTIFICATION");
//Can`t use because of Windows.UI library
ToastNotificationManager.CreateToastNotifier().Show(visual);
}
}
}
You have to fight Visual Studio pretty hard to use these UWP contracts in a Winforms app. You got off on the wrong foot right away with the wrong TargetPlatformVersion, pretty hard to recover from that. Full steps to take:
Edit the .csproj file with a text editor, Notepad will do. Insert this:
<PropertyGroup>
<TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
</PropertyGroup>
Which assumes you have the 10586 SDK version installed on your machine. Current right now, these versions change quickly. Double-check by looking in the C:\Program Files (x86)\Windows Kits\10\Include with Explorer, you see the installed versions listed in that directory.
Open the Winforms project, use Project > Add Reference > Windows tab > tick the Windows.Data and the Windows.UI contract. Add Reference again and use the Browse tab to select System.Runtime. I picked the one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\ .NETFramework\v4.6.1\Facades. This reference displays with a warning icon, not sure what it is trying to say but it doesn't appear to have any side-effects.
Test it by dropping a button on the form, double-click to add the Click event handler. The most basic code:
using Windows.UI.Notifications;
...
private void button1_Click(object sender, EventArgs e) {
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var text = xml.GetElementsByTagName("text");
text[0].AppendChild(xml.CreateTextNode("Hello world"));
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier("anythinggoeshere").Show(toast);
}
Embellish by using a different ToastTemplateType to add an image or more lines of text. Do keep in mind that your program can only work on a Win10 machine.
If anyone should happen to stumble on this, see this similar but newer post -
Toast Notifications in Win Forms .NET 4.5
Read Stepan Hakobyan's comment at the bottom.
Essentially, I'm seeing the same thing. This code runs, I can step through it line by line with no exceptions but the toast notification is never shown within a Form app.

Categories