[英]Google Cloud Speech API iOS returns 401 UNAUTHENTICATED with Firebase Storage File
I am trying to transcribe long files(>1min) using Google Cloud Speech Api from my iOS app. 我正在尝试使用iOS应用中的Google Cloud Speech Api转录长文件(> 1分钟)。
For that purpose, I do following: 为此,我要做以下工作:
1) As written in docs, I authenticate user anonymously to firebase 1)按照文档中的说明,我向Firebase匿名认证用户
[[FIRAuth auth]
signInAnonymouslyWithCompletion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
// ...
if (!error){
self.user = user;
[self.user getTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
if (!error) {
self.token = token;
[self uploadFile];
}
}];
}
}];
2) Then I upload my file to Firebase Storage and get the URI 2)然后我将文件上传到Firebase Storage并获取URI
- (void)uploadFile
{
FIRStorage * storage = [FIRStorage storage];
FIRStorageReference *storageRef = [storage reference];
FIRStorageReference *sonetRef = [storageRef child:@"transcribeTest/sonet130.mp3"];
NSData *sonet = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"sonet130" ofType:@"mp3"]];
FIRStorageUploadTask *uploadTask = [sonetRef putData:sonet metadata:nil completion:^(FIRStorageMetadata * _Nullable metadata, NSError * _Nullable error) {
if (error != nil) {
// Uh-oh, an error occurred!
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
NSURL *downloadURL = metadata.downloadURL;
NSString *path = [NSString stringWithFormat:@"gs://%@/%@",metadata.bucket,metadata.path];
NSURL * gsURL = [NSURL URLWithString:path];//@"gs://%@",downloadURL.path]];
[self trnscribeFileAtURL:gsURL];
}
}];
[uploadTask resume];
}
3) The next step should be sending Asyncrecognize request to Google Cloud Speech API. 3)下一步应该是向Google Cloud Speech API发送Asyncrecognize请求。 But I get 401 Error ''. 但我收到401错误''。
-(void)trnscribeFileAtURL:(NSURL*)url
{
NSString *service = @"https:/speech.googleapis.com/v1beta1/speech:asyncrecognize";
service = [service stringByAppendingString:@"?key="];
service = [service stringByAppendingString:API_KEY];
NSData *audioData = [NSData dataWithContentsOfFile:[self soundFilePath]];
NSDictionary *configRequest = @{@"encoding":@"LINEAR16",
@"sampleRate":@(SAMPLE_RATE),
@"languageCode":@"en-UK",
@"maxAlternatives":@30};
NSDictionary *audioRequest = @{@"uri":url.absoluteString};
NSDictionary *requestDictionary = @{@"config":configRequest,
@"audio":audioRequest};
NSError *error;
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestDictionary
options:0
error:&error];
NSString *path = service;
NSURL *URL = [NSURL URLWithString:path];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
// if your API key has a bundle ID restriction, specify the bundle ID like this:
[request addValue:[[NSBundle mainBundle] bundleIdentifier] forHTTPHeaderField:@"X-Ios-Bundle-Identifier"];
NSString *contentType = @"application/json";
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"Bearer %@",self.token] forHTTPHeaderField:@"Authorization"];
[request setHTTPBody:requestData];
[request setHTTPMethod:@"POST"];
NSURLSessionTask *task =
[[NSURLSession sharedSession]
dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(),
^{
NSString *stringResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
_textView.text = stringResult;
NSLog(@"RESULT: %@", stringResult);
});
}];
[task resume];
}
The response JSON: 响应JSON:
2017-02-28 19:58:05.837337 Speech[8057:2054726] RESULT: {
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
Looks like problem lies on this line of code: 看起来问题出在这行代码上:
[request addValue:[NSString stringWithFormat:@"Bearer %@",self.token] forHTTPHeaderField:@"Authorization"];
I am trying to pass token that I get from Firebase Anonymous auth, but it does not suit. 我正在尝试传递从Firebase匿名身份验证获得的令牌,但不适合。 I've searched the obtain I cant find how to obtain right credentials for anonymous user. 我搜索了“获取”,但找不到如何为匿名用户获取正确的凭据。 Please help. 请帮忙。
The short answer is that you can't use a Firebase Auth token to access Google APIs like Speech or Vision directly from the client. 简短的答案是,您不能使用Firebase Auth令牌直接从客户端访问Google API,例如Speech或Vision。 As the error message says, those APIs expect one of: 如错误消息所述,这些API需要以下之一:
See more info in the Speech docs on authentication . 请参阅语音文档中有关身份验证的更多信息。
The easiest way to do this is probably using something like Cloud Functions and listen for a file upload, then process the audio, and write it back to the database. 最简单的方法可能是使用Cloud Functions之类的工具 ,监听文件上传,然后处理音频,然后将其写回到数据库。
What the API_KEY? 什么是API_KEY?
You haven't mentioned it! 你还没有提到!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.