0

Trying to use Google Speech API in C# returns 403.

In Google Cloud Platform I generated a key and still getting the 403 error.

Used this code:

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();
    }
}

It's probably some invalid key issue,tried generating server key and browser key, same result, 403 (forbidden)

please help.

Alex Choroshin
  • 6,177
  • 2
  • 28
  • 36
  • Have you tried using the client library instead of making the call directly with `HttpWebRequest`? (Just trying to find the right version - https://www.nuget.org/packages/Google.Apis.CloudSpeechAPI.v1beta1/ is for v1beta1... it may be that we're looking at different APIs.) – Jon Skeet Aug 25 '16 at 07:59
  • Thanks @JonSkeet, I'll try it. – Alex Choroshin Aug 25 '16 at 08:02
  • @JonSkeet, do you have a working example using Google.Apis.CloudSpeechAPI.v1beta1 ? or even a some example for using this library? I want to use a key and not oauth2 – Alex Choroshin Aug 25 '16 at 08:16
  • I would be surprised if it supported just an API key, to be honest. I think you'll have to go the oauth2 route, but that can be pretty painless these days - download a service account key, and you can get credentials fairly easily. See https://developers.google.com/identity/protocols/application-default-credentials I don't have an example for speech at the moment, but I'm going to be working on the gRPC client very soon. (You can already build it from https://github.com/GoogleCloudPlatform/google-cloud-dotnet/tree/master/apis/Google.Cloud.Speech.V1, but I haven't looked at it personally yet.) – Jon Skeet Aug 25 '16 at 08:23
  • As you are doing a web request I would try the __curl command__ first from https://cloud.google.com/speech/docs/getting-started or check https://cloud.google.com/speech/reference/rest/ or even https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/speech. I managed to get curl, java and ios examples to work. – Clemens Tolboom Sep 01 '16 at 11:53
  • @AlexChoroshin did you find the answer i am facing the same problem – Muhammad Faizan Khan Oct 26 '16 at 09:17

3 Answers3

1

This doesn't seem to work anymore. The speech API doesn't show up.

JMA
  • 1,781
  • 9
  • 18
0

I haven't tried using the http API but here's my working code using the Google Speech API Library (Google.Apis.CloudSpeechAPI.v1beta1):

void Main()
{
    //create the service and auth
    CloudSpeechAPIService service = new CloudSpeechAPIService(new BaseClientService.Initializer
    {
        ApplicationName = "Speech API Test",
        ApiKey = "your API key..."
    });

    //configure the audio file properties
    RecognitionConfig sConfig = new RecognitionConfig();
    sConfig.Encoding = "FLAC";
    sConfig.SampleRate = 16000;
    sConfig.LanguageCode = "en-AU";

    //make the request and output the transcribed text to console
    SyncRecognizeResponse response = getResponse(service, sConfig, "audio file.flac");
    string resultText = response.Results.ElementAt(0).Alternatives.ElementAt(0).Transcript;
    Console.WriteLine(resultText);
}


public SyncRecognizeResponse getResponse(CloudSpeechAPIService sService, RecognitionConfig sConfig, string fileName)
{
    //read the audio file into a base 64 string and add to API object
    RecognitionAudio sAudio = new RecognitionAudio();
    byte[] audioBytes = getAudioStreamBytes(fileName);
    sAudio.Content = Convert.ToBase64String(audioBytes);

    //create the request with the config and audio files
    SyncRecognizeRequest sRequest = new SyncRecognizeRequest();
    sRequest.Config = sConfig;
    sRequest.Audio = sAudio;

    //execute the request
    SyncRecognizeResponse response = sService.Speech.Syncrecognize(sRequest).Execute();

    return response;
}


public byte[] getAudioStreamBytes(string fileName)
{
    FileStream fileStream = File.OpenRead(fileName);
    MemoryStream memoryStream = new MemoryStream();
    memoryStream.SetLength(fileStream.Length);
    fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
    byte[] BA_AudioFile = memoryStream.GetBuffer();
    return BA_AudioFile;
}
0

Was getting the same 403 error and below is what helped me to fix

Step 1 - Used quick start speech API documentation - https://cloud.google.com/speech/docs/getting-started and found billing was disabled. Below is the detailed error message that I have received as curl output i.e. 3rd step in the document

{
  "error": {
    "code": 403,
    "message": "Project xxxxx (#xxxxxx) has billing disabled. Please enable it.",
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developer console API key",
            "url": "https://console.developers.google.com/project/1026744225026/apiui/credential"
          }
        ]
      }
    ]
  }
}

Enabled billing for the project.

Step 2 - Make sure you are a member of chromium-dev@chromium.org i.e. step 1 as per http://www.chromium.org/developers/how-tos/api-keys (Also refer https://github.com/gillesdemey/google-speech-v2/issues/8)

Once you are member Go to your Project - > click Enable API -> Search for speech API it will have 2 results - > Enable 'Speech API Private API' (before subscribing to group you would only see 'Google Cloud Speech API' now you can see 'Speech API Private API')

Hope this helps

Ravi A.
  • 2,163
  • 2
  • 18
  • 26