14

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

SimpleVar
  • 14,044
  • 4
  • 38
  • 60
cindywmiao
  • 937
  • 2
  • 11
  • 26

1 Answers1

11

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();
        }
    }
}
Tessa Painter
  • 2,113
  • 2
  • 16
  • 21
Umo
  • 342
  • 3
  • 11
  • Still, the same exception as the old code. I could not get _HWR_SpeechToText.GetResponse() – cindywmiao Aug 13 '14 at 18:17
  • The remote server returned an error: (403) Forbidden. – cindywmiao Aug 13 '14 at 18:26
  • Hello, could you check out is the right place I got the google API key? I have add the key in my question. – cindywmiao Aug 13 '14 at 21:47
  • 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 – Umo Aug 13 '14 at 23:13
  • I think my key has some problem. so I find one from internet. It passed buut I got nothing in the response. – cindywmiao Aug 13 '14 at 23:33
  • @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](http://www.speedyshare.com/URhjK/GoogleRequest.rar) – Umo Aug 15 '14 at 15:25
  • 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. – cindywmiao Aug 15 '14 at 18:12
  • 1
    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. http://www.chromium.org/developers/how-tos/api-keys – Umo Aug 16 '14 at 12:38
  • @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? – Sanju Rao May 20 '16 at 12:00
  • I'm still getting 403, can anyone help? – Alex Choroshin Aug 24 '16 at 21:29
  • @SanjuRao have you succeeded getting any output? I'm still getting 403 error. – Alex Choroshin Aug 25 '16 at 07:43
  • @AlexChoroshin yes. – Sanju Rao Aug 25 '16 at 07:44
  • @SanjuRao , after generating a key in google cloud platform, I still getting the 403 error, can you please assist? – Alex Choroshin Aug 25 '16 at 07:46
  • @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. – Sanju Rao Aug 25 '16 at 07:47
  • @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 Oct 26 '16 at 07:22
  • getting error http://stackoverflow.com/questions/40254879/the-underlying-connection-was-closed-when-receving-google-speech-to-text-api-res – Muhammad Faizan Khan Oct 26 '16 at 07:23