2014-01-11 21 views
0

我正在調用下面的函數,使用google api將語音轉換爲文本。我在最新版本的xcode中做這件事,我爲Mac製作這個應用程序。問題是下面的函數似乎在NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];中斷,所以我無法檢查語音。我試過一個異步調度,但它似乎沒有幫助。我也嘗試了@autoreleasepool {},但它似乎也沒有幫助。任何幫助表示讚賞!NSURLConnection在目標c中未被正確調用,適用於Mac應用

-(void)processSpeech { 
    NSURL *url = [NSURL fileURLWithPath:@"/Users/marcus/Documents/testvoices/okSpeak.query.flac"]; 

    NSData *flacFile = [NSData dataWithContentsOfURL:url]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize?lang=en-US"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request addValue:@"Content-Type" forHTTPHeaderField:@"audio/x-flac; rate=16000"]; 
    [request addValue:@"audio/x-flac; rate=16000" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:flacFile]; 
    [request setValue:[NSString stringWithFormat:@"%ld",[flacFile length]] forHTTPHeaderField:@"Content-length"]; 
    NSHTTPURLResponse *urlResponse = nil; 
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil]; 
    NSString *rawData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
    NSLog(@"Raw: %@",rawData); 

    return rawData; 
} 
+0

您是否收到錯誤?沒有數據返回?還有別的嗎? – Zarathuztra

回答

2

如果你懷疑你的sendSynchronousRequest一個問題,你應該考慮至少三件事情:

  • 看那NSHTTPURLResponse對象。它報道什麼?值得注意的是,對於HTTP請求,您會看到一個statusCode,它可以提供信息。

  • 你應該傳遞一個NSError地址指針,也並確保錯誤是nil,太:

    NSError *error = nil; 
    NSHTTPURLResponse *urlResponse = nil; 
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; 
    
    if (!responseData) 
        NSLog(@"sendSynchronousRequest error: %@", error); 
    else { 
        NSLog(@"sendSynchronousRequest response = %@", urlResponse); 
        NSString *rawData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
        NSLog(@"responseData = %@", rawData); 
    } 
    
  • 你得到了什麼作爲你的rawData字符串?

順便說一句,如果你想知道,你想要的Content-Type爲報頭字段,而不是價值。

// [request addValue:@"Content-Type" forHTTPHeaderField:@"audio/x-flac; rate=16000"]; 
[request addValue:@"audio/x-flac; rate=16000" forHTTPHeaderField:@"Content-Type"];