picture box image does not change in C# - c#

I want to change picture's box image when my board(a USB module) is joined or disjoined to computer. But I think my thread will execute just one time. And picture box's image won't change.
my code:
bool boardjoined = false;
void BoardConnecion()
{
foreach (var item in SerialPort.GetPortNames())
{
if (item == "COM3")
{
boardjoined = true;
DisplayImage(_pic_usb, "on.png");
}
else
{
boardjoined = false;
DisplayImage(_pic_usb, "off.png");
}
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_pic_usb.Image = Bitmap.FromFile(Application.StartupPath + #"\off.png");
new Thread(new ThreadStart(BoardConnecion)).Start();
}
private void DisplayImage(PictureBox pic, string picName)
{
pic.Invoke(new EventHandler(delegate
{
pic.Image = Bitmap.FromFile(Application.StartupPath +#"\" + picName);
}));
}

You can do a never ending loop in the BoardConnection.
void BoardConnecion()
{
while(true)
{
foreach (var item in SerialPort.GetPortNames())
{
if (item == "COM3")
{
boardjoined = true;
DisplayImage(_pic_usb, "on.png");
}
else
{
boardjoined = false;
DisplayImage(_pic_usb, "off.png");
}
}
Thread.Sleep(500);
}
}
You should proabably add a safety switch to get out of the loop to. =)

you can use below mentioned code
private System.Timers.Timer timerClock = new System.Timers.Timer();
timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
timerClock.Interval = 1000;
timerClock.Enabled = true;
public void OnTimer( Object source, ElapsedEventArgs e )
{
foreach (var item in SerialPort.GetPortNames())
{
if (item == "COM3")
{
boardjoined = true;
DisplayImage(_pic_usb, "on.png");
}
else
{
boardjoined = false;
DisplayImage(_pic_usb, "off.png");
}
}
}

Related

Play/Stop MP3 Queue with Naudio or other

I have a problem to stop/pause a Mp3 Queue. Any help please?
I use this class from Githup. it work fine but can't stop it:
public class playr
{
private Queue<string> playlist;
private IWavePlayer player = new WaveOutEvent();
private WaveStream fileWaveStream;
public playr()
{
}
public playr(List<string> startingPlaylist)
{
playlist = new Queue<string>(startingPlaylist);
}
public void PlaySong()
{
if (playlist.Count < 1)
{
return;
}
if (player != null && player.PlaybackState != PlaybackState.Stopped)
{
player.Stop();
}
if (fileWaveStream != null)
{
fileWaveStream.Dispose();
}
if (player != null)
{
player.Dispose();
player = null;
}
player = new WaveOutEvent();
fileWaveStream = new NAudio.Wave.Mp3FileReader(playlist.Dequeue(), new Mp3FileReader.FrameDecompressorBuilder(waveFormat => new NLayer.NAudioSupport.Mp3FrameDecompressor(waveFormat)));
var stream = new BlockAlignReductionStream(fileWaveStream);
player.Init(fileWaveStream);
player.Play();
player.PlaybackStopped += (sender, evn) => { PlaySong(); };
}
}
I popup mp3 files from a datagridview. The goal is playing mp3 sounds and drawing charts.
private void Play_Click(object sender, EventArgs e)
{
try
{
playlist = new List<string>();
for (int item = 0; item < dataGridView1.Rows.Count - 1; item++)
{
playlist.Add(#"mp3Conversion\sounds\" + dataGridView1.Rows[item].Cells["mp3"].Value.ToString());
}
playr playr = new playr(playlist);
playr.PlaySong();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
It wont to stop when I click stop button. is there a way to add a notifier or manage queue ?
private void btnStop_Click(object sender, EventArgs e)
{
try
{
var playr = new playr(playlist);
playr.stopit();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
I hope it's not too late to help you
You can't pause, because you are losing the reference to the object defining a new object
You could try to define the object as static object to solve this problem, but you have to be very careful disposing the object or access to it from multi thread
A very little example
public class playr
{
private Queue<string> playlist;
public static IWavePlayer player = new WaveOutEvent();
// private WaveStream fileWaveStream;
public playr()
{
}
public playr(List<string> startingPlaylist)
{
playlist = new Queue<string>(startingPlaylist);
}
public void PlaySong()
{
if (playlist.Count < 1)
{
return;
}
if (player != null && player.PlaybackState != PlaybackState.Stopped)
{
player.Stop();
}
if (player != null)
{
player.Dispose();
player = null;
}
player = new WaveOutEvent();
var audioFilePath = playlist.First();
var fileWaveStream = new AudioFileReader(audioFilePath);
player.Init(fileWaveStream);
player.Play();
player.PlaybackStopped += (sender, evn) => { PlaySong(); };
}
}
Then you can handle the "player" object from form view

Form is opening in Background once the Splash Screen is getting closed

I have created a splash screen. On my splash screen I have given a progress bar and two buttons to perform some action. On button click I am displaying respective forms once the modules of those forms are getting loaded completely along with showing the progress on progress bar. Once the respective form will open, Splash screen shall be closed and Form should be shown on top of the screen.
But the issue is that after the splash screen closing, My form is opening in background or you can say getting out of focus which should not happen. I have checked various solutions given on google or stackoverflow but could not able to resolve my problem.
Following is my code :
SplashScreen.cs
// <--- Data Members
// --->
public SplashScreen()
{
InitializeComponent();
this.Opacity = 0.0;
UpdateTimer.Interval = TIMER_INTERVAL;
UpdateTimer.Start();
this.ClientSize = this.BackgroundImage.Size;
}
static public void ShowSplashScreen()
{
if (ms_frmSplash != null)
{
return;
}
ms_oThread = new Thread(new ThreadStart(SplashScreen.ShowForm));
ms_oThread.IsBackground = true;
ms_oThread.SetApartmentState(ApartmentState.STA);
ms_oThread.Start();
while (ms_frmSplash == null || ms_frmSplash.IsHandleCreated == false)
{
System.Threading.Thread.Sleep(TIMER_INTERVAL);
}
}
static public void CloseForm()
{
if (ms_frmSplash != null && ms_frmSplash.IsDisposed == false)
{
ms_frmSplash.m_dblOpacityIncrement = -ms_frmSplash.m_dblOpacityDecrement;
}
ms_oThread = null;
ms_frmSplash = null;
}
static public void SetStatus(string newStatus)
{
SetStatus(newStatus, true);
}
static public void SetStatus(string newStatus, bool setReference)
{
if (ms_frmSplash == null)
{
return;
}
ms_frmSplash.m_sStatus = newStatus;
if (setReference)
{
ms_frmSplash.SetReferenceInternal();
}
}
static public void SetReferencePoint()
{
if (ms_frmSplash == null)
{
return;
}
ms_frmSplash.SetReferenceInternal();
}
static private void ShowForm()
{
ms_frmSplash = new SplashScreen();
Application.Run(ms_frmSplash);
}
private void SetReferenceInternal()
{
if (m_bDTSet == false)
{
m_bDTSet = true;
m_dtStart = DateTime.Now;
ReadIncrements();
}
double dblMilliseconds = ElapsedMilliSeconds();
m_alActualTimes.Add(dblMilliseconds);
m_dblLastCompletionFraction = m_dblCompletionFraction;
if (m_alPreviousCompletionFraction != null && m_iIndex < m_alPreviousCompletionFraction.Count)
{
m_dblCompletionFraction = (double)m_alPreviousCompletionFraction[m_iIndex++];
}
else
{
m_dblCompletionFraction = (m_iIndex > 0) ? 1 : 0;
}
}
private double ElapsedMilliSeconds()
{
TimeSpan ts = DateTime.Now - m_dtStart;
return ts.TotalMilliseconds;
}
private void ReadIncrements()
{
string sPBIncrementPerTimerInterval = SplashScreenXMLStorage.Interval;
double dblResult;
if (Double.TryParse(sPBIncrementPerTimerInterval, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dblResult) == true)
{
m_dblPBIncrementPerTimerInterval = dblResult;
}
else
{
m_dblPBIncrementPerTimerInterval = .0015;
}
string sPBPreviousPctComplete = SplashScreenXMLStorage.Percents;
if (sPBPreviousPctComplete != "")
{
string[] aTimes = sPBPreviousPctComplete.Split(null);
m_alPreviousCompletionFraction = new ArrayList();
for (int i = 0; i < aTimes.Length; i++)
{
double dblVal;
if (Double.TryParse(aTimes[i], System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dblVal) == true)
{
m_alPreviousCompletionFraction.Add(dblVal);
}
else
{
m_alPreviousCompletionFraction.Add(1.0);
}
}
}
else
{
m_bFirstLaunch = true;
m_sTimeRemaining = "";
}
}
private void StoreIncrements()
{
string sPercent = "";
double dblElapsedMilliseconds = ElapsedMilliSeconds();
for (int i = 0; i < m_alActualTimes.Count; i++)
{
sPercent += ((double)m_alActualTimes[i] / dblElapsedMilliseconds).ToString("0.####", System.Globalization.NumberFormatInfo.InvariantInfo) + " ";
}
SplashScreenXMLStorage.Percents = sPercent;
m_dblPBIncrementPerTimerInterval = 1.0 / (double)m_iActualTicks;
SplashScreenXMLStorage.Interval = m_dblPBIncrementPerTimerInterval.ToString("#.000000", System.Globalization.NumberFormatInfo.InvariantInfo);
}
public static SplashScreen GetSplashScreen()
{
return ms_frmSplash;
}
private void UpdateTimer_Tick(object sender, System.EventArgs e)
{
if (Program.isRadarSelected)
{
if (count >= 100)
{
UpdateTimer.Stop();
this.Close();
}
else
{
updateProgressBar();
count += 5;
}
}
if (m_dblOpacityIncrement > 0)
{
m_iActualTicks++;
if (this.Opacity < 1)
{
this.Opacity += m_dblOpacityIncrement;
}
}
else
{
if (this.Opacity > 0)
{
this.Opacity += m_dblOpacityIncrement;
}
else
{
StoreIncrements();
UpdateTimer.Stop();
this.Close();
}
}
}
private void updateProgressBar()
{
SplashScreen.SetStatus("Loading : " + count + " %");
statusLabel.Text = m_sStatus;
m_dblLastCompletionFraction += m_dblPBIncrementPerTimerInterval;
int width = (int)Math.Floor(statusPanel.ClientRectangle.Width * m_dblLastCompletionFraction);
int height = statusPanel.ClientRectangle.Height;
int x = statusPanel.ClientRectangle.X;
int y = statusPanel.ClientRectangle.Y;
if (width > 0 && height > 0)
{
m_rProgress = new Rectangle(x, y, width, height);
if (!statusPanel.IsDisposed)
{
Graphics g = statusPanel.CreateGraphics();
LinearGradientBrush brBackground = new LinearGradientBrush(m_rProgress, Color.FromArgb(58, 96, 151), Color.FromArgb(181, 237, 254), LinearGradientMode.Horizontal);
g.FillRectangle(brBackground, m_rProgress);
g.Dispose();
}
}
}
private void RadarSelectionButton_Click(object sender, EventArgs e)
{
Program.isButtonClicked= true;
}
Program.cs
internal static class Program
{
public static bool isButtonClicked= false;
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashScreen.ShowSplashScreen();
Application.DoEvents();
while (!isButtonClicked)
{
System.Threading.Thread.Sleep(50);
}
Application.Run(new MyForm());
SplashScreen.CloseForm();
}
}
As far as I remember Application.Run(...) is blocking, meaning that your splash screen would never close before the main window is closed. You could try the code below. Let me know how it goes.
internal static class Program
{
public static bool isButtonClicked= false;
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashScreen.ShowSplashScreen();
Application.DoEvents();
while (!isButtonClicked)
{
System.Threading.Thread.Sleep(50);
}
var window = new MyForm();
window.Load += (s, e) =>
{
SplashScreen.CloseForm();
window.Activate();
}
Application.Run(window);
}
}
Regarding you CloseForm method, I am unsure how you intended it to work. The only thing you are doing is setting the opacity? But as far as you write this is not your issue. But I would think that you need to signal the main window of the splash screen to close, before the Application.Run(..) would exit.
And also the while loop in the ShowSplashScreen method; Why? Consider using stuff like ManualResetEvent for waiting and signaling between threads. Always better to wait for an event rather than polling.

Why when reporting progress with backgroundworker it's never get to the progresschanged event?

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.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace Search_Text_In_Files
{
public partial class Form1 : Form
{
StreamWriter w = new StreamWriter(#"e:\textresults.txt");
ProgressBarWithText pbt = new ProgressBarWithText();
public Form1()
{
InitializeComponent();
pbt.Size = new Size(984, 23);
pbt.Location = new Point(12, 358);
this.Controls.Add(pbt);
backgroundWorker1.RunWorkerAsync();
}
bool result = false;
public List<string> FindLines(string DirName, string TextToSearch)
{
int counter = 0;
List<string> findLines = new List<string>();
DirectoryInfo di = new DirectoryInfo(DirName);
List<FileInfo> l = new List<FileInfo>();
CountFiles(di, l, count =>
{
backgroundWorker1.ReportProgress(count, "Counting Files");
});
int totalFiles = l.Count;
int countFiles = 0;
if (di != null && di.Exists)
{
if (CheckFileForAccess(DirName) == true)
{
foreach (FileInfo fi in l)
{
backgroundWorker1.ReportProgress((int)((double)countFiles / totalFiles * 100.0), fi.Name);
countFiles++;
System.Threading.Thread.Sleep(1);
if (string.Compare(fi.Extension, ".cs", true) == 0)
{
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains(TextToSearch))
{
counter++;
findLines.Add(s);
result = true;
backgroundWorker1.ReportProgress(0, fi.FullName);
}
}
}
}
}
}
}
return findLines;
}
private void CountFiles(DirectoryInfo di, List<FileInfo> l, Action<int> CurrentCount) {
foreach (DirectoryInfo dir in di.GetDirectories())
CountFiles(dir, l, currentCount=> {
CurrentCount(l.Count);
});
}
private bool CheckForAccess(string PathName)
{
if (File.Exists(PathName) == true)
return CheckFileForAccess(PathName);
if (Directory.Exists(PathName) == true)
return CheckFolderForAccess(PathName);
return false;
}
private bool CheckFileForAccess(string FileName)
{
FileSecurity fs = new FileSecurity(FileName, AccessControlSections.Access);
if (fs == null)
return false;
AuthorizationRuleCollection TheseRules = fs.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckFolderForAccess(string FolderName)
{
DirectoryInfo di = new DirectoryInfo(FolderName);
if (di == null)
return false;
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.Access);
if (acl == null)
return false;
AuthorizationRuleCollection TheseRules = acl.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckACL(AuthorizationRuleCollection TheseRules)
{
foreach (FileSystemAccessRule ThisRule in TheseRules)
{
if ((ThisRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
{
if (ThisRule.AccessControlType == AccessControlType.Deny)
return false;
}
}
return true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FindLines(#"d:\c-sharp", "FileShellExtension");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState.ToString() == "Counting Files")
label2.Text = e.UserState.ToString();
pbt.Value = e.ProgressPercentage;
pbt.Text = e.ProgressPercentage.ToString() + "%";
pbt.Invalidate();
label2.Text = e.UserState.ToString();
if (result == true)
{
listView1.Items.Add(e.UserState.ToString());
result = false;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
}
else if (e.Error != null)
{
}
else
{
}
}
public class ProgressBarWithText : ProgressBar
{
const int WmPaint = 15;
SizeF TextSize;
PointF TextPos;
bool dontpaint = false;
public ProgressBarWithText()
{
this.DoubleBuffered = true;
this.TextChanged += ProgressBarWithText_TextChanged;
this.SizeChanged += ProgressBarWithText_SizeChanged;
}
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
void RecalcTextPos()
{
if (this.IsDisposed == true)
return;
if (string.IsNullOrEmpty(base.Text))
return;
using (var graphics = Graphics.FromHwnd(this.Handle))
{
TextSize = graphics.MeasureString(base.Text, this.Font);
TextPos.X = (this.Width / 2) - (TextSize.Width / 2);
TextPos.Y = (this.Height / 2) - (TextSize.Height / 2);
}
}
void ProgressBarWithText_SizeChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
void ProgressBarWithText_TextChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (dontpaint == false)
{
switch (m.Msg)
{
case WmPaint:
using (var graphics = Graphics.FromHwnd(Handle))
graphics.DrawString(base.Text, base.Font, Brushes.Black, TextPos.X, TextPos.Y);
break;
}
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams result = base.CreateParams;
result.ExStyle |= 0x02000000; // WS_EX_COMPOSITED
return result;
}
}
}
}
}
The method FindLines i call it form the dowork event:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FindLines(#"d:\c-sharp", "FileShellExtension");
}
And in the FindLines method i'm using the reportprogress in two places:
CountFiles(di, l, count =>
{
backgroundWorker1.ReportProgress(count, "Counting Files");
});
int totalFiles = l.Count;
int countFiles = 0;
if (di != null && di.Exists)
{
if (CheckFileForAccess(DirName) == true)
{
foreach (FileInfo fi in l)
{
backgroundWorker1.ReportProgress((int)((double)countFiles / totalFiles * 100.0), fi.Name);
But it's never get to the progresschanged event.
I checked in the designer the property: WorkerReportsProgress is set to true.

Kinect Speech Recognition not Working

I have a program that when the user says "Start" or "Stop", the program makes a skeleton display on the screen. I use the same code as the Shape Game, and it works fine there, but not on my code. I dont know which part of the code doesn't work since this is my first time eith speech recognition programming. Thanks for your help(Sorry if my code is messy)Recognizing the Speech
public class SpeechRecognizer : IDisposable
{
private KinectAudioSource kinectAudioSource;
private struct WhatSaid
{
public Verbs Verb;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.Stop();
if (this.sre != null)
{
// NOTE: The SpeechRecognitionEngine can take a long time to dispose
// so we will dispose it on a background thread
ThreadPool.QueueUserWorkItem(
delegate(object state)
{
IDisposable toDispose = state as IDisposable;
if (toDispose != null)
{
toDispose.Dispose();
}
},
this.sre);
this.sre = null;
}
this.isDisposed = true;
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public EchoCancellationMode EchoCancellationMode
{
get
{
this.CheckDisposed();
return this.kinectAudioSource.EchoCancellationMode;
}
set
{
this.CheckDisposed();
this.kinectAudioSource.EchoCancellationMode = value;
}
}
public static SpeechRecognizer Create()
{
SpeechRecognizer recognizer = null;
try
{
recognizer = new SpeechRecognizer();
}
catch (Exception)
{
// speech prereq isn't installed. a null recognizer will be handled properly by the app.
}
return recognizer;
}
private void CheckDisposed()
{
if (this.isDisposed)
{
throw new ObjectDisposedException("SpeechRecognizer");
}
}
public void Stop()
{
this.CheckDisposed();
if (this.sre != null)
{
this.kinectAudioSource.Stop();
this.sre.RecognizeAsyncCancel();
this.sre.RecognizeAsyncStop();
this.sre.SpeechRecognized -= this.SreSpeechRecognized;
this.sre.SpeechHypothesized -= this.SreSpeechHypothesized;
this.sre.SpeechRecognitionRejected -= this.SreSpeechRecognitionRejected;
}
}
public void Start(KinectAudioSource kinectSource)
{
this.CheckDisposed();
this.kinectAudioSource = kinectSource;
this.kinectAudioSource.AutomaticGainControlEnabled = false;
this.kinectAudioSource.BeamAngleMode = BeamAngleMode.Adaptive;
var kinectStream = this.kinectAudioSource.Start();
this.sre.SetInputToAudioStream(
kinectStream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
this.sre.RecognizeAsync(RecognizeMode.Multiple);
}
public enum Verbs
{
None = 0,
Start,
Stop,
Resume,
Pause
}
private bool isDisposed;
private readonly Dictionary<string, WhatSaid> speechCommands = new Dictionary<string, WhatSaid>
{
{ "Start", new WhatSaid { Verb = Verbs.Start } },
{ "Stop", new WhatSaid { Verb = Verbs.Stop } },
{ "Resume", new WhatSaid { Verb = Verbs.Resume } },
{ "Pause", new WhatSaid { Verb = Verbs.Pause } },
};
private SpeechRecognitionEngine sre;
private static RecognizerInfo GetKinectRecognizer()
{
Func<RecognizerInfo, bool> matchingFunc = r =>
{
string value;
r.AdditionalInfo.TryGetValue("Kinect", out value);
return "True".Equals(value, StringComparison.InvariantCultureIgnoreCase) && "en-US".Equals(r.Culture.Name, StringComparison.InvariantCultureIgnoreCase);
};
return SpeechRecognitionEngine.InstalledRecognizers().Where(matchingFunc).FirstOrDefault();
}
private SpeechRecognizer()
{
RecognizerInfo ri = GetKinectRecognizer();
this.sre = new SpeechRecognitionEngine(ri);
this.LoadGrammar(this.sre);
}
private void LoadGrammar(SpeechRecognitionEngine speechRecognitionEngine)
{
// Build a simple grammar of shapes, colors, and some simple program control
var single = new Choices();
foreach (var phrase in this.speechCommands)
{
single.Add(phrase.Key);
}
var objectChoices = new Choices();
objectChoices.Add(single);
var actionGrammar = new GrammarBuilder();
actionGrammar.AppendWildcard();
actionGrammar.Append(objectChoices);
var allChoices = new Choices();
allChoices.Add(actionGrammar);
allChoices.Add(single);
// This is needed to ensure that it will work on machines with any culture, not just en-us.
var gb = new GrammarBuilder { Culture = speechRecognitionEngine.RecognizerInfo.Culture };
gb.Append(allChoices);
var g = new Grammar(gb);
speechRecognitionEngine.LoadGrammar(g);
speechRecognitionEngine.SpeechRecognized += this.SreSpeechRecognized;
speechRecognitionEngine.SpeechHypothesized += this.SreSpeechHypothesized;
speechRecognitionEngine.SpeechRecognitionRejected += this.SreSpeechRecognitionRejected;
}
private void SreSpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
var said = new SaidSomethingEventArgs { Verb = Verbs.None, Matched = "?" };
this.SetLabel("Word not Recognized.... Try 'Start', 'Stop', 'Pause' or 'Resume'");
if (this.SaidSomething != null)
{
this.SaidSomething(new object(), said);
}
}
private void SreSpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
{
this.SetLabel("I think you said: " + e.Result.Text);
}
public event EventHandler<SaidSomethingEventArgs> SaidSomething;
private void SreSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
this.SetLabel("\rSpeech Recognized: \t" + e.Result.Text);
if ((this.SaidSomething == null) || (e.Result.Confidence < 0.3))
{
return;
}
var said = new SaidSomethingEventArgs { Verb = 0, Phrase = e.Result.Text };
foreach (var phrase in this.speechCommands)
{
if (e.Result.Text.Contains(phrase.Key) && (phrase.Value.Verb == Verbs.Pause))
{
//pause = true;
break;
}
else if ((e.Result.Text.Contains(phrase.Key) && (phrase.Value.Verb == Verbs.Resume)))
{
//resume = true;
break;
}
else if ((e.Result.Text.Contains(phrase.Key) && (phrase.Value.Verb == Verbs.Start)))
{
//start = true;
break;
}
else if ((e.Result.Text.Contains(phrase.Key) && (phrase.Value.Verb == Verbs.Stop)))
{
//stop = true;
break;
}
}
// Look for a match in the order of the lists below, first match wins.
List<Dictionary<string, WhatSaid>> allDicts = new List<Dictionary<string, WhatSaid>> { this.speechCommands };
bool found = false;
for (int i = 0; i < allDicts.Count && !found; ++i)
{
foreach (var phrase in allDicts[i])
{
if (e.Result.Text.Contains(phrase.Key))
{
found = true;
break;
}
}
}
if (!found)
{
return;
}
}
public class SaidSomethingEventArgs : EventArgs
{
public Verbs Verb { get; set; }
public string Phrase { get; set; }
public string Matched { get; set; }
}
public event Action<string> SetLabel = delegate { };
}
In my Code
private void RecognizeSaidSomething(object sender, SpeechRecognizer.SpeechRecognizer.SaidSomethingEventArgs e)
{
FlyingText.FlyingText.NewFlyingText(this.skeleton.Width / 30, new Point(this.skeleton.Width / 2, this.skeleton.Height / 2), e.Matched);
switch (e.Verb)
{
case SpeechRecognizer.SpeechRecognizer.Verbs.Pause:
pause = true;
break;
case SpeechRecognizer.SpeechRecognizer.Verbs.Resume:
resume = true;
break;
case SpeechRecognizer.SpeechRecognizer.Verbs.Start:
start = true;
break;
case SpeechRecognizer.SpeechRecognizer.Verbs.Stop:
stop = true;
break;
}
}
It doesn't look like you ever call RecognizeSaidSomething() from SreSpeechRecognized(). You create the event args:
var said = new SaidSomethingEventArgs { Verb = 0, Phrase =
e.Result.Text };
But it doesn't appear that you do anything with it.
The foreach loop below that doesn't seem to serve any purpose, you test for the phrase then just break out of the loop. You don't set any variables or call any functions in that loop that I can see.
Then there is a for loop that appears to do something similar to the foreach loop (just in a different manner). It searches for matches to the recognized phrase, but then doesn't do anything with what it finds. It just returns.
I would think somewhere in the SreSpeechRecognized() event handler you want to call RecognizeSaidSomething() and pass it the SaidSomethingEventArgs.

How to use a thread in a playback function

I want to playback a sound file in two or three external sound cards at the same time and I think that using threads is the solution but I really didn't know how to use it in the playback code.
This is the event makes on button play:
public partial class PlaybackForm : Form
{
IWavePlayer waveOut;
string fileName = null;
WaveStream mainOutputStream;
WaveChannel32 volumeStream;
int _deviceNum;
int _deviceNum1;
Thread t1;
Thread t2;
public PlaybackForm(int deviceNum,int deviceNum1)
{
InitializeComponent();
_deviceNum = deviceNum;
_deviceNum1 = deviceNum1;
}
private void buttonPlay_Click(object sender, EventArgs e)
{
if (waveOut != null)
{
if (waveOut.PlaybackState == PlaybackState.Playing)
{
return;
}
else if (waveOut.PlaybackState == PlaybackState.Paused)
{
waveOut.Play();
return;
}
}
// we are in a stopped state
// TODO: only re-initialise if necessary
if (String.IsNullOrEmpty(fileName))
{
toolStripButtonOpenFile_Click(sender, e);
}
if (String.IsNullOrEmpty(fileName))
{
return;
}
try
{
CreateWaveOut();
}
catch (Exception driverCreateException)
{
MessageBox.Show(String.Format("{0}", driverCreateException.Message));
return;
}
mainOutputStream = CreateInputStream(fileName);
trackBarPosition.Maximum = (int)mainOutputStream.TotalTime.TotalSeconds;
labelTotalTime.Text = String.Format("{0:00}:{1:00}", (int)mainOutputStream.TotalTime.TotalMinutes,
mainOutputStream.TotalTime.Seconds);
trackBarPosition.TickFrequency = trackBarPosition.Maximum / 30;
try
{
waveOut.Init(mainOutputStream);
}
catch (Exception initException)
{
MessageBox.Show(String.Format("{0}", initException.Message), "Error Initializing Output");
return;
}
// not doing Volume on IWavePlayer any more
volumeStream.Volume = volumeSlider1.Volume;
waveOut.Play();
}
And this is how to create the waveout:
private void CreateWaveOut()
{
CloseWaveOut();
int latency = (int)comboBoxLatency.SelectedItem;
//if (radioButtonWaveOut.Checked)
{
//WaveCallbackInfo callbackInfo = checkBoxWaveOutWindow.Checked ?
WaveCallbackInfo callbackInfo = WaveCallbackInfo.FunctionCallback();
// WaveCallbackInfo callbackInfo = WaveCallbackInfo.FunctionCallback();
// WaveCallbackInfo.NewWindow(): WaveCallbackInfo.FunctionCallback();
WaveOut outputDevice = new WaveOut(callbackInfo);
outputDevice.DesiredLatency = latency;
outputDevice.DeviceNumber = _deviceNum;
waveOut = outputDevice;
}
}
I declared two deviceNum but until now I can playsound only in one device,that's why I want to use thread.
Can you help me please
Thank you in advance
Do something like that:
using System.Threading;
...
private void buttonPlay_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(this.PlaySound), 1);
ThreadPool.QueueUserWorkItem(new WaitCallback(this.PlaySound), 2);
}
private void PlaySound(object obj)
{
int deviceNumber = (int)obj;
// Do the stuff you used to do in buttonPlay_Click
WaveOut myWaveOut = CreateWaveOut(deviceNumber);
...
}
private WaveOut CreateWaveOut(int deviceNumber)
{
...
WaveOut outputDevice = new WaveOut(callbackInfo);
outputDevice.DesiredLatency = latency;
outputDevice.DeviceNumber = _deviceNum;
return outputDevice;
}

Categories