Я пытаюсь записать аудиофайл в моем приложении, затем хочу загрузить на веб-сервер код, который я написал, работает для записи и воспроизведения и даже для загрузка на веб-сервер с использованием PHP, единственные проблемы, с которыми мне приходится сталкиваться, что загруженный файл всегда пуст, размер файла ZEROЗагрузите записанный аудиофайл в Objective-C с помощью PHP
Можете ли вы посмотреть мой код и сообщить мне, что я делаю неправильно, чтобы вызвать этот вопрос
Все ниже работает отлично, единственная часть, с которой я борюсь, когда файл загружен, он отображается в папке назначения сервера, но размер файла ZERO, я также являюсь атташе ng my 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.";
};
?>
Пожалуйста, узнайте, как форматировать ваш вопрос правильно. Вы видели это? – borrrden
Извините за это, я думаю, теперь это выглядит хорошо. – majarmeh
Намного лучше! Благодаря! – borrrden