C# speech recognition (System.Speech.Recognition) issues - c#

I've been working with a bit of speech recognition for a few days with various test programs and it's all worked fine. However i've tried implementing it into my OpenGL project and the function 'Recognized' is now not being called.
Up in the Windows Speech Recognition thing (the thing that says "try saying 'Start Listening'" an awful lot), words that are loaded appear when i say them, so I am assuming that it is correctly detecting words, it's just for some reason not triggering the event.
Here's the code i've been using. All you really need to know (besides what is shown in the code), is that AddCommands is called somewhere else, to add in a few words that i've been testing with and that 'Initiate' is called upon the loading of the form.
public class SpeechControls
{
public static SpeechRecognizer sRecognizer;
private static Dictionary<string, IVoiceControlable> controllers = new Dictionary<string, IVoiceControlable>();
public static void Initiate()
{
sRecognizer = new SpeechRecognizer();
sRecognizer.Enabled = true;
sRecognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(Recognized);
}
private static void Recognized(object obj, SpeechRecognizedEventArgs args)
{
controllers[args.Result.Text].TriggerCommand(args.Result.Text);
}
public static void AddCommands(string[] commands, IVoiceControlable control)
{
foreach (string str in commands)
{
controllers.Add(str, control);
}
sRecognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(commands))));
}
}
Does anyone know why 'Recognized' would not be triggered?
Thanks for any help, much appreciated.

Because OpenGL runs of game loops rather than event listening, the thread is completely taken up by the loop. To start listening for commands a second thread is needed.

Related

How to Run script when unity load just once?

Here, I am looking for a piece of code in the Unity editor that will execute the initial panel of the created package only once when Unity is opened, but this code is executed in the initial frame every time I play Unity and then stop it, and it continuously shows the panel. Gives. I want it to be seen only once when the project is opened.
[InitializeOnLoad]
public class Autorun
{
static Autorun()
{
EditorApplication.update += RunOnce;
}
static void RunOnce()
{
Debug.Log("Once"); // but it will repeat every time I Clicking on play then stop it.
Panel.Init();
EditorApplication.update -= RunOnce;
}
}
Above is the code suggested by the user in Unity Answers, which was chosen as the best answer, but in fact, as I pointed out, it had a problem.
Although it was mentioned in the comment that the second answer in Unity answers solves the problem, after a while I noticed that the panel opens again when saving the code and I could not find a way to block it through another condition in EditorApplication. The solution below is the final method of solving the problem that uses EditorPrefs and I feel it necessary to share this method with you.
internal const string FIRST_TIME = "FIRST_TIME"; // the key
static Autorun()
{
EditorApplication.update += RunOnce;
EditorApplication.quitting += Quit;
}
private static void Quit() => EditorPrefs.DeleteKey(FIRST_TIME);
private static void RunOnce()
{
var firstTime = EditorPrefs.GetBool(FIRST_TIME, true);
Debug.Log(firstTime);
if (firstTime)
{
EditorPrefs.SetBool(FIRST_TIME, false);
if (EditorPrefs.GetBool(Panel.ShowOnStart, true)) Panel.Init();
}
EditorApplication.update -= RunOnce;
}
}

Unity AdMob ads not displayed

I'm making a game on Unity 5.5 and I've followed Google's Official AdMob Getting Started Guide to integrate AdMob into my game (currently iOS-only, but Android will also follow when I get this working).
I've set up my game at the AdMob console and created a reward-based video ad.
I've added the GoogleMobileAds.framework into my built project in Xcode.
I've made sure I'm linking against the newly-added framework too.
Downloaded the Unity package and integrated it into my project as required.
I've hooked up to event handlers: My ad gets loaded with no problem, no failure.
When I try to display the ad on iOS, ad.IsLoaded(); returns false even though it has just loaded (my OnAdLoaded event of the ad is firing). In Unity editor, I'm seeing the expected dummy methods being called at correct order (though nothing is being displayed, which I think is the expected behavior on Unity's own editor).
Here is my code for loading ads (of course, my publisher and ad unit IDs are redacted):
public class AdManager : MonoBehaviour {
static RewardBasedVideoAd ad;
static UIManager uiManager;
#if UNITY_ANDROID
static string adUnitId = "ca-app-pub-XXX/YYY";
#elif UNITY_IPHONE
static string adUnitId = "ca-app-pub-XXX/YYY";
#else
static string adUnitId = "unexpected_platform";
#endif
static int headstartPoints;
// Use this for initialization
void Start () {
uiManager = GameObject.Find("Scripts").GetComponent<UIManager>();
ad = RewardBasedVideoAd.Instance;
ad.OnAdRewarded += Ad_OnAdRewarded;
ad.OnAdClosed += Ad_OnAdClosed;
ad.OnAdFailedToLoad += Ad_OnAdFailedToLoad;
ad.OnAdLoaded += Ad_OnAdLoaded;
headstartPoints = 0;
RequestNewAd();
}
void Ad_OnAdFailedToLoad (object sender, AdFailedToLoadEventArgs e)
{
Debug.Log("Ad failed to load.");
}
void Ad_OnAdLoaded (object sender, System.EventArgs e)
{
Debug.Log("Ad loaded.");
}
void Ad_OnAdClosed (object sender, System.EventArgs e)
{
Debug.Log("Ad was closed, proceeding to game without rewards...");
}
void Ad_OnAdRewarded (object sender, Reward e)
{
Debug.Log("Ad rewarded.");
headstartPoints = (int)e.Amount;
}
public static int GetAndConsumeRewards(){
int points = headstartPoints;
headstartPoints = 0;
return points;
}
public static void RequestNewAd(){
Debug.Log("Requested new ad.");
AdRequest request = new AdRequest.Builder().Build();
ad.LoadAd(request, adUnitId);
}
public static void DisplayAdOrProceed(){
if(ad.IsLoaded()){
ad.Show();
Debug.Log("Ad was loaded, displaying ad...");
}else{
Debug.Log("Ad wasn't loaded, skipping ad...");
uiManager.ProceedToGame();
}
}
// Update is called once per frame
void Update () {
}
}
I've never seen OnAdFailedToLoad method being called, and I always see OnAdLoaded being called, so there doesn't seem to be a problem there. But when I check ad.IsLoaded() after ad is loaded, for some weird reason it's false. Please note that RewardBasedVideoAd is a singleton object as stated in Google's docs.
What am I doing wrong?
UPDATE: I am calling RequestNewAd() as soon as the app starts and also on each "level" start (think of it like one level is roughly ~30 seconds) and DisplayAdOrProceed() on death (e.g. end of the level). When DisplayAdOrProceed() is called, the ad's loaded method is always called (unless I have a connection problem but that's not the case here).
UPDATE 2: Just noticed that there is a really suspicious stack trace on "ad load" event:
Ad loaded.
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
AdManager:Ad_OnAdLoaded(Object, EventArgs)
System.EventHandler`1:Invoke(Object, TEventArgs)
GoogleMobileAds.Api.RewardBasedVideoAd:<RewardBasedVideoAd>m__8(Object, AdFailedToLoadEventArgs)
System.EventHandler`1:Invoke(Object, TEventArgs)
GoogleMobileAds.iOS.RewardBasedVideoAdClient:RewardBasedVideoAdDidFailToReceiveAdWithErrorCallback(IntPtr, String)
I can see that the ad load event is fired from a method named for a failure handler (RewardBasedVideoAdDidFailToReceiveAdWithErrorCallback, GoogleMobileAds.Api.RewardBasedVideoAd:<RewardBasedVideoAd>m__8(Object, AdFailedToLoadEventArgs)). However, it's calling the ad load event and not any failure handler. I have no idea what's going on or if it's a poorly-designed naming convention or not.
Okay after diving literally into the IL2CPP-generated C++ code in the Xcode project, I've realized that the SDK is calling the incorrect method. The ad is failing to load with error "No ad to show", but incorrectly firing up the ad load method. I'll make additional changes to my code to detect if it's being loaded correctly.
Terrible bug (or design decision), Google. I hope this gets fixed soon.

Directx device doesn't initialize for window, Program hang

I've tried following several tutorials an have seem to be having trouble.
I've got an existing program that i'm trying to add a directx window to as an additional popup forum that will run as a child to the main application form.
Here is the windows form class:
public partial class DxWindow : Form
{
Device device;
public DxWindow()
{
InitializeComponent();
initDevice();
}
private void initDevice()
{
MessageBox.Show("hello");
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, pp);
}
private void Render()
{
//render stuff
}
private void DxWindow_Paint(object sender, PaintEventArgs e)
{
Render();
}
}
and here is where i initialize the form (from a UI button in main window)
private void toolStripButton3_Click_1(object sender, EventArgs e)
{
if (DirectxWindow == null)
{
DirectxWindow = new DxWindow();
DirectxWindow.Show();
}
}
When i run the program and click the button. it seems create the form in memory but never shows up. when i step through it in the debugger, it gets to "DirectxWindow = new DxWindow();" and then automatically jumps out of break mode and continues running with the main window frozen and no new Dxwindow().
when i break execution is seems to still be on "DirectxWindow = new DxWindow();"
Also, "MessageBox.Show("hello");" in the DxWindow constructor is never called"
Edit: I've deduced that as soon as it hits "PresentParameters pp = new Microsoft.DirectX.Direct3D.PresentParameters();" the application becomes unresponsive without throwing any errors.
Turns out my problem was needing to use
<startup useLegacyV2RuntimeActivationPolicy="true">
in the "App.config" File
Solution was found here: Mixed mode assembly is built against version 'v1.1.4322'
Although i never got the error as described by the OP. i simply had this problem as described in the comments:
"Thank you!!!! This is the weirdest problem I'd ever encountered. In VS 2012 .Net 4.0 my application would just hang the moment I initialized any variable of a type related to this DLL. I'd never seen anything like it. Couldn't find anything about the problem until I found this!" – Quinxy von Besiex

Proximity device handler only fires once (WP8)

I made a program that handles NFC tags back in 2013, today after two years of pause on that program i continued with it, and ran into some strange problem. In the program i read NFC tags which are writen with a "window.Someid" so they are app specific.
For some reason, the program works perfectly when scanning the NFC tag, except, when i want to scan the tag for the second time, the handler doesn't fire. any idea what causes this? (i see no error message).
Here's my code:
ProximityDevice PDevice;
private long SubscriptionID = -1;
// Constructor
public MainPage()
{
InitializeComponent();
PDevice = ProximityDevice.GetDefault();
// subscribe for messages
SubscriptionID = PDevice.SubscribeForMessage("Windows.SomeMsg", ProximityMessageRcvd);
}
private void ProximityMessageRcvd(ProximityDevice sender, ProximityMessage message)
{
Debug.WriteLine("Message");
}

UI Forms events block my other STOCK TICKER API events - how can I prevent this?

I have an API (dll) that collects stock ticks via an event mechanism. Such as below:
...
using MT4API;
public partial class Blue : Form
{
...
public Blue()
{
...
string symbol = "GBPUSD";
MT4DDE dde = new MT4DDE("");
dde.OnQuote += new System.EventHandler<QuoteEventArgs>(MT_OnQuote);
dde.Connect();
dde.Subscribe(symbol);
....
The idea is that on each chart tick I get an event. here is the event handler code:
private static void MT_OnQuote(object sender, QuoteEventArgs args)
{
GlobalClass.Ask = args.Ask;
GlobalClass.Bid = args.Bid;
// I have back ground worker code that updatestables from the global class
}
This all works fine. So long as I do not touch any other buttons on the form UI. As soon as I click a button on the form of the UI... I no longer receive events from my API, the UI application functions normally, but with no data from the API.
Why do events from the UI stop any further events coming from the API event?
Any idea whats going on here? Or suggestions how to design this?
Does the same problem occur if you comment out your code that updates the tables from the global object? and if you comment out the background worker?
It would be a good idea to distinguish if the event stops being fired just after you press some button on the UI, or if it stops being fired only after some line of code you wrote is being executed.
In order to be able to help you, we would need to know how the event on the MT4DDE class is triggered.
If you have the code for this class, posting it would help.
If you don't you may want to use a tool such as Reflector to decompile the assembly into C# and see what the MT4DDE class is doing that might cause it to stop invoking the event.
In addition, if you are doing anything related to background threads, or if you're doing anything unusual with your application's main message loop, it would be a good idea to mention it here.
I have tried to use the invoke command, it works, but after a few events it stops...here is the code isolated:
using MT4API;
namespace WindowsFormsApplication1
{
public delegate void UpdateTextCallback(double ask, double bid);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string symbol = "GBPUSD";
MT4DDE dde = new MT4DDE("");
dde.OnQuote += new EventHandler<QuoteEventArgs>(MT_OnQuote);
dde.Connect();
dde.Subscribe(symbol);
}
private void updateTickDisplay(double ask, double bid)
{
textBox1.Text = ask.ToString();
textBox2.Text = bid.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void MT_OnQuote(object sender, QuoteEventArgs args)
{
BeginInvoke(new UpdateTextCallback(this.updateTickDisplay),
new object[] { args.Ask, args.Bid });
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox3.Text = textBox1.Text;
}
}
}
The only difference from the real code is that I am using a data grid....as opposed to a text field. But it is clear that the UI blocks somehow the new events. It is strange that I get about 5 to 10 events and then it just stops. Strange. Any ideas on a differnet design?

Categories

Resources