使用API​​密钥在C#上通过GRPC验证Google Cloud Speech

时间:2018-10-01 21:20:33

标签: c# interceptor google-speech-api

我想在GRPC上的C#上实现流语音识别,但是只有一个API KEY

这种类型的键-> https://cloud.google.com/docs/authentication/api-keys

通过搜索网络,我知道他们可以使用其他语言(Android,IO)“拦截”并添加带有以下关键字的标头:

Metadata.Key.of(“ x-goog-api-key”,“ value”);

我如何在c#中进行相同的操作?

我的代码(如果出于任何原因需要)。

public static async Task<object> StreamingRecognizeAsync(Stream audio)
    {
        var speech = SpeechClient.Create();

        var streamingCall = speech.StreamingRecognize();


        // Write the initial request with the config.
        await streamingCall.WriteAsync(
            new StreamingRecognizeRequest()
            {
                StreamingConfig = new StreamingRecognitionConfig()
                {
                    Config = new RecognitionConfig()
                    {
                        Encoding =
                        RecognitionConfig.Types.AudioEncoding.Linear16,
                        SampleRateHertz = 16000,
                        LanguageCode = "en",
                    },
                    InterimResults = true,
                }
            });
        // Print responses as they arrive.
        Task printResponses = Task.Run(async () =>
        {
            while (await streamingCall.ResponseStream.MoveNext(
                default(CancellationToken)))
            {
                foreach (var result in streamingCall.ResponseStream
                    .Current.Results)
                {
                    foreach (var alternative in result.Alternatives)
                    {
                        Console.WriteLine(alternative.Transcript);
                    }
                }
            }
        });

        var buffer = new byte[32 * 1024];
        int bytesRead;

        while ((bytesRead = await audio.ReadAsync(
                buffer, 0, buffer.Length)) > 0)
        {
            await streamingCall.WriteAsync(
                new StreamingRecognizeRequest()
                {
                    AudioContent = Google.Protobuf.ByteString
                    .CopyFrom(buffer, 0, bytesRead),
                });
            await Task.Delay(500);
        };

        await streamingCall.WriteCompleteAsync();
        await printResponses;
        return 0;
    }

非常感谢您

1 个答案:

答案 0 :(得分:0)

gRPC允许每次调用传递其他设置。 在您的情况下,以下方法可以解决问题:

speech.StreamingRecognize(Google.Api.Gax.Grpc.CallSettings.FromHeader("x-goog-api-key", YOUR_API_KEY));

(注意:您确定它是 x-goog-api-key 而不是 x-api-key 吗?)