Search code examples
iosnsurlconnectionspeech-recognitionnsdatansurlrequest

How to store .flac file content in NSData?


In my app I have added one .flac file in my resources folder. I want to send to this .flac file to Google's speech recognition service... Below is my code:

NSURL* urlGoogle = [NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize"];

NSMutableURLRequest *urlGoogleRequest = [[NSMutableURLRequest  alloc]initWithURL:urlGoogle];

[urlGoogleRequest setHTTPMethod:@"POST"];

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

NSURLResponse* response = nil;

NSError* error = nil;

    NSArray *docDirs = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [docDirs objectAtIndex:0];
    NSString *path = [[docDir stringByAppendingPathComponent:@"surround88"]
                         stringByAppendingPathExtension:@"flac" ];

    NSURL* url = [NSURL fileURLWithPath:path];

//Here I'm getting flacData value is nil

NSData *flacData = [NSData dataWithContentsOfURL:url]; //flacData = nil

    [urlGoogleRequest setHTTPBody:flacData];
    NSData* googleResponse = [NSURLConnection sendSynchronousRequest:urlGoogleRequest
                                                   returningResponse:&response
                                                               error:&error];
    id jsonObject=[NSJSONSerialization JSONObjectWithData:googleResponse options:kNilOptions error:nil];
    NSLog(@"Googles response is: %@",jsonObject);

Since I'm not sending any data to the server, I'm getting empty response.

I have tested other 3rd party apis like openears, dragon, ispeech etc and not satisfied.

Can some one help me how to proceed to further. Is this the correct way to implement google's speech recognition functionality? Any help would be appreciated.


Solution

  • Since you're placing the file in your resources folder, you're not going to find it with NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);. That's why [NSData dataWithContentsOfURL:url] is returning nil.

    Your file is now placed in your Bundle, so try loading the file's contents with this:

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"surround88" withExtension:@"flac"];
    NSData *flacData = [NSData dataWithContentsOfURL:url];
    

    EDIT: based on comments bellow

    Make sure the file is a member of the target you're building. In other words:

    Managing resources and targets in Xcode

    1. Select your .flac file
    2. Make sure to check the boxes for the targets you're testing this with

    Using the test project above, I was able to successfully create an NSData object from the .flac file.