2017-02-28 94 views
0

我正嘗試使用Google雲語音API從我的iOS應用程序轉錄長文件(> 1分鐘)。
爲此,我做以下操作:谷歌雲語音API iOS返回401未經認證的Firebase存儲文件

1)寫在文檔,我驗證用戶以匿名方式向火力點

[[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)然後我上傳我的文件,以火力地堡的存儲和獲取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)下一步應該向Google Cloud Speech API發送Asyncrecognize請求。但我得到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]; 

} 

響應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" 
    } 
} 

看來問題就出在這行代碼:

[request addValue:[NSString stringWithFormat:@"Bearer %@",self.token] forHTTPHeaderField:@"Authorization"]; 

我試圖令牌傳遞,我從火力地堡匿名權威性得到,但它不適合。我搜索了獲得我無法找到如何獲得匿名用戶的正確憑據。請幫忙。

回答

2

簡而言之,您無法使用Firebase身份驗證令牌直接從客戶端訪問語音或視覺等Google API。由於錯誤消息指出,這些API期待之一:

  • 谷歌的OAuth 2.0(用戶發起或通過服務帳戶)
  • 登錄cookie

the Speech docs on authentication更多信息。

最簡單的方法是使用類似Cloud Functions的東西,監聽文件上傳,然後處理音頻,並將其寫回數據庫。

+0

謝謝你讓它變得清晰並給予替代方式。 –

0

什麼是API_KEY?

你還沒有提到它!