3

我正在尝试在我的应用程序中录制音频文件,然后我想上传到 Web 服务器,我编写的代码可用于录制和播放,甚至可以使用 PHP 上传到 Web 服务器,这是我唯一的问题面对上传的文件总是空白,文件大小为零

你能看看我的代码,让我知道我做错了什么导致这个问题

下面的一切都运行良好,当文件上传到服务器的目标文件夹中时,我唯一苦苦挣扎的部分,但文件大小为零,我还在帖子末尾附加了我的 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.";
        }; 
    ?>
4

2 回答 2

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.

于 2013-06-24T04:44:16.507 回答
0

您可以使用此替代解决方案:

NSData *mediaContent = [[NSFileManager defaultManager] contentsAtPath:_mediaURL.absoluteString];
于 2017-07-06T09:43:27.757 回答