How to use google speech recognition api in c#?

25,415

Just tested this myself, below is a working solution if you have a valid API key.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net;
    using System.IO;

    namespace GoogleRequest
    {
     class Program
     {
        static void Main(string[] args)
        {
            try
            {

                FileStream fileStream = File.OpenRead("good-morning-google.flac");
                MemoryStream memoryStream = new MemoryStream();
                memoryStream.SetLength(fileStream.Length);
                fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
                byte[] BA_AudioFile = memoryStream.GetBuffer();
                HttpWebRequest _HWR_SpeechToText = null;
                _HWR_SpeechToText =
                            (HttpWebRequest)HttpWebRequest.Create(
                                "https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=YOUR_API_KEY_HERE");
                _HWR_SpeechToText.Credentials = CredentialCache.DefaultCredentials;
                _HWR_SpeechToText.Method = "POST";
                _HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
                _HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
                Stream stream = _HWR_SpeechToText.GetRequestStream();
                stream.Write(BA_AudioFile, 0, BA_AudioFile.Length);
                stream.Close();

                HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();
                if (HWR_Response.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
                    Console.WriteLine(SR_Response.ReadToEnd());
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }
    }
}
Share:
25,415
cindywmiao
Author by

cindywmiao

Updated on July 15, 2022

Comments

  • cindywmiao
    cindywmiao almost 2 years

    I want to get the audio file from c# and send to google speech recognition API for get the "speech to text" answer.

    My code is like this:

    try
    {                
        byte[] BA_AudioFile = GetFile(filename);              
        HttpWebRequest _HWR_SpeechToText = null;
        _HWR_SpeechToText =
                    (HttpWebRequest)HttpWebRequest.Create(
                        "https://www.google.com/speech-api/v2/recognize?output=json&lang=" + DEFAULT_LANGUAGE + "&key=" + key);
        _HWR_SpeechToText.Credentials = CredentialCache.DefaultCredentials;
        _HWR_SpeechToText.Method = "POST";
        _HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
        _HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
        Stream stream = _HWR_SpeechToText.GetRequestStream();
        stream.Write(BA_AudioFile, 0, BA_AudioFile.Length);
        stream.Close();
    
        HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();
        if (HWR_Response.StatusCode == HttpStatusCode.OK)
        {
            StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
            Console.WriteLine(SR_Response.ToString());
        }
    
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    

    This part is for upload the file.wav and get the response for the google API, which I find from Internet.

    But my code always catches the exceptions:

    you must write content length bytes to the request stream before calling at _HWR_SpeechToText.GetResponse(); But I already wroteh the ContextLength.

    So my question is why my program failed? It's because the google link or the HTTPWebRequest I used inappropriately?

    Is this the right place I got the API key?

    enter image description here

    • Nikolay Shmyrev
      Nikolay Shmyrev almost 10 years
      How big is your file? Did you try with a smaller one?
    • cindywmiao
      cindywmiao almost 10 years
      @NikolayShmyrev I test the file from github.com/gillesdemey/google-speech-v2
    • Nikolay Shmyrev
      Nikolay Shmyrev almost 10 years
      Which file exactly, there are 3 of them in audio folder
    • Nikolay Shmyrev
      Nikolay Shmyrev almost 10 years
      Also, do you really have / after rate line in your code?
    • cindywmiao
      cindywmiao almost 10 years
      @NikolayShmyrev good-morning-google.flac, and I try the other two, it's the same.
    • SimpleVar
      SimpleVar over 9 years
      Have you tried not setting the content length? From what I understand, it is set automatically when you write to the request stream anyways. Maybe manually setting it beforehand messes it up. (By the way, you should really hide vulnerable information like your API key, email, etc - I took the liberty to do it here)
    • Muhammad Faizan Khan
      Muhammad Faizan Khan over 7 years
      @cindywmiao I am unable to run how did you validated your API key? i guess m facing same error
  • cindywmiao
    cindywmiao almost 10 years
    Still, the same exception as the old code. I could not get _HWR_SpeechToText.GetResponse()
  • cindywmiao
    cindywmiao almost 10 years
    The remote server returned an error: (403) Forbidden.
  • cindywmiao
    cindywmiao almost 10 years
    Hello, could you check out is the right place I got the google API key? I have add the key in my question.
  • Umo
    Umo almost 10 years
    Yes, the key for server applications is the right one, but you have to enable the Speech API aswell, the option to do should be under API's & Auth --> APIs. I see that you have a IP specified aswell, and i seems to be a private one, try removing any IP and it should allow access from any IP
  • cindywmiao
    cindywmiao almost 10 years
    I think my key has some problem. so I find one from internet. It passed buut I got nothing in the response.
  • Umo
    Umo almost 10 years
    @cindywmiao Updated my answer again and here is a link to the whole project, your should be about to download, add your API key and just run it to see the response. link to project
  • cindywmiao
    cindywmiao almost 10 years
    I still think the problem comes from the API key. Because I use my key, it give me an exception, I find one other key from Internet, it give me nothing. I use your code, it's the same thing.
  • Umo
    Umo almost 10 years
    You need to subscribe as a chromium dev aswell i think, i followed the instructions on this site, otherwise you cant activate the right api in the developer console and your key wont work. chromium.org/developers/how-tos/api-keys
  • Sanju Rao
    Sanju Rao almost 8 years
    @Umo I get the out put as only {"result":[]}. I don see any output result. I have used the same code that is here. Can you please help me if i am missing to do anything extra?
  • Alex Choroshin
    Alex Choroshin over 7 years
    I'm still getting 403, can anyone help?
  • Alex Choroshin
    Alex Choroshin over 7 years
    @SanjuRao have you succeeded getting any output? I'm still getting 403 error.
  • Sanju Rao
    Sanju Rao over 7 years
    @AlexChoroshin yes.
  • Alex Choroshin
    Alex Choroshin over 7 years
    @SanjuRao , after generating a key in google cloud platform, I still getting the 403 error, can you please assist?
  • Sanju Rao
    Sanju Rao over 7 years
    @AlexChoroshin I may need time to go back to my repository to see the solution give me some time. I will get back to u on this.
  • Muhammad Faizan Khan
    Muhammad Faizan Khan over 7 years
    @Umo you code is not working and showing error on repsonse line that "The underlying connection was closed: An unexpected error occurred on a receive."
  • Muhammad Faizan Khan
    Muhammad Faizan Khan over 7 years