objective-c - 发送录制音频 POST

标签 objective-c ios avaudiorecorder

我用 AVAudioRecorder 录制音频:

  audioRecorder = nil;

//Initialize audio session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

//Override record to mix with other app audio, background audio not silenced on record
OSStatus propertySetError = 0;
UInt32 allowMixing = true;
propertySetError = AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(allowMixing), &allowMixing);

UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);

NSLog(@"Mixing: %lx", propertySetError); // This should be 0 or there was an issue somewhere

[[AVAudioSession sharedInstance] setActive:YES error:nil];

NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] initWithCapacity:0];

if (recordEncoding == ENC_PCM) {
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM]  forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0]              forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt:2]                      forKey:AVNumberOfChannelsKey];

    [recordSetting setValue:[NSNumber numberWithInt:16]                     forKey:AVLinearPCMBitDepthKey];
    [recordSetting setValue:[NSNumber numberWithBool:NO]                    forKey:AVLinearPCMIsBigEndianKey];
    [recordSetting setValue:[NSNumber numberWithBool:NO]                    forKey:AVLinearPCMIsFloatKey];
} else {

    NSNumber *formatObject;

    switch (recordEncoding) {
        case ENC_AAC:
            formatObject = [NSNumber numberWithInt:kAudioFormatMPEG4AAC];
            break;

        case ENC_ALAC:
            formatObject = [NSNumber numberWithInt:kAudioFormatAppleLossless];
            break;

        case ENC_IMA4:
            formatObject = [NSNumber numberWithInt:kAudioFormatAppleIMA4];
            break;

        case ENC_ILBC:
            formatObject = [NSNumber numberWithInt:kAudioFormatiLBC];
            break;

        case ENC_ULAW:
            formatObject = [NSNumber numberWithInt:kAudioFormatULaw];
            break;

        default:
            formatObject = [NSNumber numberWithInt:kAudioFormatAppleIMA4];
            break;
    }

    [recordSetting setValue:formatObject                                forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0]          forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt:2]                  forKey:AVNumberOfChannelsKey];
    [recordSetting setValue:[NSNumber numberWithInt:12800]              forKey:AVEncoderBitRateKey];

    [recordSetting setValue:[NSNumber numberWithInt:16]                 forKey:AVLinearPCMBitDepthKey];
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];

}

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recDir = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", recDir]];

NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&error];

if (!audioRecorder) {
    NSLog(@"audioRecorder: %@ %d %@", [error domain], [error code], [[error userInfo] description]);
    return;
}

//    audioRecorder.meteringEnabled = YES;
//
BOOL audioHWAvailable = audioSession.inputAvailable;
if (! audioHWAvailable) {
    UIAlertView *cantRecordAlert =
    [[UIAlertView alloc] initWithTitle: @"Warning"
                               message: @"Audio input hardware not available"
                              delegate: nil
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
    [cantRecordAlert show];
    return;
}

if ([audioRecorder prepareToRecord]) {
    [audioRecorder record];
    NSLog(@"recording");
} else {
    //        int errorCode = CFSwapInt32HostToBig ([error code]);
    //        NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);
    NSLog(@"recorder: %@ %d %@", [error domain], [error code], [[error userInfo] description]);
}

我想在 POST header 中发送它。我怎样才能正确地做到这一点?我猜我应该有 NSData,然后将它转换成 NSString。我对吗?如果为真,我如何将 AVAudioRecorder 输出转换为 NSData

最佳答案

这是我为理解音频文件上传所做的示例应用程序。 您可以使用以下方法使用 POST 发送录制的音频:

- (IBAction) pushLoader
  {
    NSURL *pathURL = urlOfAudioFile; //File Url of the recorded audio
    NSData *voiceData = [[NSData alloc]initWithContentsOfURL:pathURL];
    NSString *urlString = @"http://iroboticshowoff.com/img2/upload.php"; // You can give your url here for uploading
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]init]autorelease];

    @try
    {
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];
        NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\".caf\"\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:voiceData]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];

        [request setHTTPBody:body];

        NSError *error = nil;
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
        UIAlertView *alert = nil;
        if(error)
            {
            alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"Error in Uploading the File" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        }
        else
            {
            NSLog(@"Success %@",returnString);
            alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"File get uploaded" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        }
        [alert show];
        [alert release];
        alert = nil;
        [returnString release];
        returnString = nil;
        boundary = nil;
        contentType = nil;
        body = nil;     
    }
    @catch (NSException * exception)
     {
        NSLog(@"pushLoader in ViewController :Caught %@ : %@",[exception name],[exception reason]);
    }
    @finally
    {
        [voiceData release];
        voiceData = nil;
        pathURL = nil;
        urlString = nil;
    }
}

关于objective-c - 发送录制音频 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13006897/

相关文章:

cocoa - AVAudioRecorder 无法在 OS X Mavericks 上录制

ios - popview 上消失的 UIButtons

ios - 从 UIImagePickerController 中选取时的 UIImage 大小变化

objective-c - FBNativeDialog 不支持 Facebook sdk 3.1

php - 无法在 Objective-C 中检索 json 数据

ios - ld : library not found for -lDoubleConversion React Native 0. 59

ios - 如何访问 iOS 中动态传递给子 viewController 的参数?

iphone - IOS中UI实现查询

ios - AVAudioRecorder 在来自后台后不会附加录音

iphone - 在设备上录制时收到 ConvertInput 使用无效 anchor 时间错误