使用PHP在Objective-C上传录制的音频文件

时间:2013-06-24 04:28:29

标签: ios audio upload avfoundation

我正在尝试在我的应用中录制音频文件,然后我想上传到网络服务器, 我写的代码用于记录和回放,甚至用于使用PHP上传到Web服务器,我面临的唯一问题是上传的文件总是空白,ZERO文件大小

请您查看我的代码,让我知道我做错了什么导致此问题

下面的所有内容都运行得非常好,我在文件上传时遇到的唯一一件事就出现在服务器的目标文件夹中,但是ZERO文件大小,我也在帖子的末尾添加了我的php。

- (void)viewDidLoad {
    [super viewDidLoad];

    // Disable Stop/Play button when application launches
    [btnStop setEnabled:NO];
    [btnPlay setEnabled:NO];

    // Set the audio file
    NSArray *pathComponents = [NSArray arrayWithObjects: [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], @"MyAudioMemo.m4a", nil];
    //NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];

    // Setup audio session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    // Define the recorder setting
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

    // Initiate and prepare the recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];

}

- (IBAction)record:(id)sender {
    // Stop the audio player before recording
    if (player.playing) {
        [player stop];
    }

    if (!recorder.recording) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];

        // Start recording
        [recorder record];
        [btnRecord setTitle:@"Pause" forState:UIControlStateNormal];

    } else {

        // Pause recording
        [recorder pause];
        [btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    }

    [btnStop setEnabled:YES];
    [btnPlay setEnabled:NO];
}

- (IBAction)stop:(id)sender {
    [recorder stop];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
}

- (IBAction)play:(id)sender {
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
        [player setDelegate:self];
        [player play];
    }
}

- (IBAction)upload:(id)sender {
    NSData *file1Data = [[NSData alloc] initWithContentsOfFile:[recorder.url absoluteString]];
    NSString *urlString = @"http://mydomain.com/phpcodes/uploadFile.php";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------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:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"AudioFile3.m4a\"\r\n"]] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:file1Data]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:body];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"Return String= %@",returnString);
}

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully (BOOL)flag{
    [btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    [btnStop setEnabled:NO];
    [btnPlay setEnabled:YES];
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Done"
                                                    message: @"Finish playing the recording!"
                                                   delegate: nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

PHP代码

    <?php
        $folder = "audio/";

        if (is_uploaded_file($_FILES['userfile']['tmp_name']))  {   
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $folder.$_FILES['userfile']['name'])) {
            Echo "File uploaded";
        } else {
            Echo "File not moved to destination folder. Check permissions";
        };
        } else {
            Echo "File is not uploaded.";
        }; 
    ?>

2 个答案:

答案 0 :(得分:3)

问题很可能在于这一行:

NSData *file1Data = [[NSData alloc] initWithContentsOfFile:[recorder.url absoluteString]];

initWithContentsOfFile:方法需要文件路径,但是您传入的是表示文件URL的字符串。

试试这个:

NSData *file1Data = [[NSData alloc] initWithContentsOfFile:[recorder.url path]];

或:

NSData *file1Data = [[NSData alloc] initWithContentsOfURL:recorder.url];

使用调试器将有助于解决此问题。在upload:方法中设置断点并检查每个变量的值。您很可能会看到file1Datanil

答案 1 :(得分:0)

您可以使用此备用解决方案:

NSData *mediaContent = [[NSFileManager defaultManager] contentsAtPath:_mediaURL.absoluteString];