March 12, 2011

Separate ID's using comma then pass to database

This is simple console program which is used to built only for any sycnerio in which we have to bulk of ID's in string and pass that ID's into database by breaking each ID after comma.

Here's the code

static void Main(string[] args)
{
Console.WriteLine("Please enter name of friut by comma separated");

string data = Console.ReadLine();

string[] dataNos = data.Trim().Split(new char[] { ',' });
for (int i = 0; i < dataNos.Length; i++)
{
if (dataNos[i] != "")
{
string result = dataNos[i];
Console.WriteLine(result);
}
}

Console.ReadLine();
}

English to Native language Transalator

This program is based on Console Application using C#.Net Framework 4.0. This program using Google Transaltion API and you get your transaltion API from Code.Google.com

Here's Code

static void Main(string[] args)
{
Console.WriteLine("Please write some thing here to be translate");

string text = Console.ReadLine();
string fromLanguage = "en"; //English
string toLanguage = "es"; // Spanish
string apiKey = ""; // Enter your APIKey here
string apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
string url = string.Format(apiUrl, apiKey, fromLanguage, toLanguage, text);

var translateLanguage = new Translate();
string returnData = translateLanguage.TranslateLanguage(url);
Console.WriteLine("Your translate sentence in spanish is: \n" + returnData);

Console.ReadLine();
}

Class Code

public class Translate
{
public string TranslateLanguage(string url)
{
string returnString = string.Empty;

try
{
WebRequest request = HttpWebRequest.Create(url);
request.Method = "GET";

using (WebResponse response = request.GetResponse())
{
using (var streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
returnString = streamReader.ReadToEnd();
}
}
}
catch (Exception exception)
{
Console.Out.WriteLine(exception.Message);
}
return returnString;
}
}

Playback Sound

This program is based on Windows Form Application using C#.Net Framework 4.0. The conclusion of this program is to built a such type of application who save your voice at runtime and playback your voice after stop saving that voice also user has an option of saving the recoding at the time of play-back.

For this purpose you have to include Microsoft SAPI dll file add in Refernce of your project. For add reference right click on reference in solution explorer then click on reference and on Tab named Browse go to this path

C:\Program Files\Common Files\\Microsoft shared\Speech\Sapi.dll

To enable us to reference the required namespaces directly from code.

using System.Diagnostics;
using System.Threading;
using SpeechLib;

For Creating User Interface you need following controls

3 Buttons named as;

Start -----> btnStart
Stop -----> btnStop
Replay-----> btnReplay

1 checkbox named as

Checkbox -----> chkSaveVoice

1 Textbox named as txtText (Multiline = true)

The GUI of form is as follow;

Playback-Sound-Image

Add these members in form class

private SpeechLib.SpSharedRecoContext objRecoContext;
private SpeechLib.ISpeechRecoGrammar grammar;
private string strData="No recording yet";

Here's the code

public void RecoContext_Recognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result)
{
strData = Result.PhraseInfo.GetText(0, -1, true);
Debug.WriteLine("Recognition: " + strData + ", " + StreamNumber + ", " + StreamPosition);
txt.Text = strData;
}

private void btnStartDictation_Click(object sender, EventArgs e)
{
try
{
if (objRecoContext == null)
{
objRecoContext = new SpeechLib.SpSharedRecoContext();
objRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler(RecoContext_Recognition);
grammar = objRecoContext.CreateGrammar(1);
grammar.DictationLoad("", SpeechLoadOption.SLOStatic);
}

grammar.DictationSetState(SpeechRuleState.SGDSActive);
}

catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show("Error occurred: " + ex.ToString(),"Error");
}
}

private void btnStopDictation_Click(object sender, EventArgs e)
{
grammar.DictationSetState(SpeechRuleState.SGDSInactive);
}

private void btnReplay_Click(object sender, EventArgs e)
{
try
{
SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
SpVoice Voice = new SpVoice();
if (chkSaveReplay.Checked)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "All files (*.*)|*.*|wav files (*.wav)|*.wav";
sfd.Title = "Save to a wave file";
sfd.FilterIndex = 2;
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
SpFileStream SpFileStream = new SpFileStream();
SpFileStream.Open(sfd.FileName, SpFileMode, false);
Voice.AudioOutputStream = SpFileStream;
Voice.Speak("You recorded the following message " + strData, SpFlags);
Voice.WaitUntilDone(Timeout.Infinite);
SpFileStream.Close();
}
}
else
{
Voice.Speak("You recorded the following message" + strData, SpFlags);
}
}
catch
{
MessageBox.Show("Speak error", "SimpleTTS", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Important Notes

Every time the Start Dictation button is clicked, we set the DictationState of the grammar object to active.

Every time the Stop Dictation button is clicked, we just sets the DictationSetState of the grammar object to Inactive.

This program saves the recognized words and append the user voice input to the textbox and save it to our string member variable.

If user selected to save the playback recording using checkbox by checked then we display a Save File Dialog and save the user’s playback to the file.

March 11, 2011

Text-to-Speech Recognition (TTS)

There is a lot of examples having place on internet about text-to-speech recognition. Mostly are in vb.net or other source. But here i am introducing code in C#.Net Framework 4.0.


I am using Microsoft Speech SDK 5.1 or you can use built-in SAPI which is already install in every type of windows. This is Windows Form Application using C# and you have to add following controls in your form

3 Buttons named as;
  • Start ----> btnStart
  • Stop ----> btnStop
  • Exit ----> btnExit

1 combo box named as;
  • cmbInstalledVoice (Dropdown style = dropdownlist)

2 Trach control named as;
  • Volume -----> btnVolume (Set minimum = 0 and maximum = 100)
  • Rate -----> btnRate (Set minimum = -10 and maximum = 10)

1 Textbox named as;
  • TextBox ------> txtVoiceText (multiline = true)

Here's also the sketch of form including these controls
Text-To-Speech-Image

Now add web reference in your project, For Web Reference
Right click on reference in solution explorer then click on Add Reference, in tab name .Net add reference name System.Speech

C# Code:


using System.Speech.Synthesis;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Diagnostics;

private SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();

private void Form1_Load(object sender, EventArgs e)
{
    ReadOnlyCollection(installedvoice) getInstalledVoice = speechSynthesizer.GetInstalledVoices(CultureInfo.CurrentCulture);
    VoiceInfo voiceInfo = getInstalledVoice[0].VoiceInfo;

    foreach (InstalledVoice installedVoice in getInstalledVoice)
    {
       voiceInfo = installedVoice.VoiceInfo;
       cmbInstalledVoice.Items.Add(voiceInfo.Name.ToString());
    }
}
private void btnStart_Click(object sender, EventArgs e)
{
   speechSynthesizer.SelectVoice(cmbInstalledVoice.Text);
   speechSynthesizer.SpeakAsync(txtVoiceText.Text);
}

private void btnVolume_ValueChanged(object sender, EventArgs e)
{
   speechSynthesizer.Volume = btnVolume.Value;
}

private void btnRate_ValueChanged(object sender, EventArgs e)
{
   speechSynthesizer.Rate = btnRate.Value;
}

private void btnStop_Click(object sender, EventArgs e)
{
   speechSynthesizer.SpeakAsyncCancelAll();
}

private void btnExit_Click(object sender, EventArgs e)
{
   this.Close();
}

March 3, 2011

Convert JSON Date to Standard Date Format

Many peoples asked about JSON date conversion into Javascript code or Jquery
Code. The method is very simple and easy. When ever you insert Date into
database using Json and when you retrieve that date from database its in Json
Format which is some thing like that:

My input Date is : 14/2/2011 (for example)
My output Date is : /Date(1297246301973)/ (for example)

So here problems create when u update that date into database again its cause error.
Here's is simple code to formulate the actual date as you inserted before

var date = /Date(1297246301973)/;
var parsedDate = new Date(parseInt(date.substr(6)));
var newDate = new Date(parsedDate);

var getMonth = newDate.getMonth();
var getDay = newDate.getDay();
var getYear = newDate.getYear();

var standardDate = getMonth + '/' + getDay + '/' + getYear;

Now you got your date according to you format....:)