将AVAudioRecorder发送到服务器iOS

将AVAudioRecorder发送到服务器iOS,第1张

概述我在过去几天尝试将一个本地保存的sounde记录上传到服务器(用一个php文件将其保存到服务器上). 问题是我找不到办法做到这一点. 在录制声音(AVAudioRecorder)时,它会保存在“NSTemporaryDirectory()”中: NSURL *temporaryRecFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stri 我在过去几天尝试将一个本地保存的sounde记录上传到服务器(用一个PHP文件将其保存到服务器上).
问题是我找不到办法做到这一点.

在录制声音(AVAudioRecorder)时,它会保存在“NstemporaryDirectory()”中:

NSURL *temporaryRecfile = [NSURL fileURLWithPath:[NstemporaryDirectory() stringByAppendingPathComponent:[Nsstring stringWithFormat:@"Voicefile"]]];

现在,我检查答案的地方都是使用ASIHTTPRequest.
但问题是ios6不支持它.

还有一些其他的库,但无论我尝试什么和如何,没有任何作用.
如果有人能帮助我,我会很高兴…

这是我的代码:

VIEwController.h

#import <UIKit/UIKit.h>#import <AVFoundation/AVFoundation.h>#import <CoreAudio/CoreAudioTypes.h>@interface VIEwController : UIVIEwController <AVAudioRecorderDelegate,AVAudioPlayerDelegate>{    UIbutton *recordbutton;    UIbutton *playbutton;    UIbutton *uploadfile;    UILabel *recStateLabel;    BOol isNotRecording;    NSURL *temporaryRecfile;    AVAudioRecorder *recorder;    AVAudioPlayer *player;}@property (nonatomic,retain) IBOutlet UIbutton *uploadfile;@property (nonatomic,retain) IBOutlet UIbutton *playbutton;@property (nonatomic,retain) IBOutlet UIbutton *recordbutton;@property (nonatomic,retain) IBOutlet UILabel *recStateLabel;-(IBAction)recording;-(IBAction)playback;-(IBAction)upload;@end

VIEwController.m

#import "VIEwController.h"#import <AVFoundation/AVFoundation.h>#import "SThttpRequest.h"@interface VIEwController ()@end@implementation VIEwController @synthesize recordbutton,playbutton,uploadfile,recStateLabel;-(IBAction)recording{    if(isNotRecording)    {        isNotRecording = NO;        [recordbutton setTitle:@"Stop" forState:UIControlStatenormal];        playbutton.hIDden = YES;        recStateLabel.text = @"Recording";        temporaryRecfile = [NSURL fileURLWithPath:[NstemporaryDirectory() stringByAppendingPathComponent:[Nsstring stringWithFormat:@"Voicefile"]]];        NSDictionary *recordSettings = [NSDictionary                                        dictionaryWithObjectsAndKeys:                                        [NSNumber numberWithInt:AVAudioQualityMin],AVEncoderAudioQualityKey,[NSNumber numberWithInt:16],AVEncoderBitRateKey,[NSNumber numberWithInt: 2],AVNumberOfChannelsKey,[NSNumber numberWithfloat:44100.0],AVSampleRateKey,nil];        recorder = [[AVAudioRecorder alloc]initWithURL:temporaryRecfile settings:recordSettings error:nil];        [recorder setDelegate:self];        [recorder preparetoRecord];        [recorder record];    }    else    {        isNotRecording = YES;        [recordbutton setTitle:@"Rec" forState:UIControlStatenormal];        playbutton.hIDden = NO;        recStateLabel.text = @"Not Recording";        [recorder stop];    }}-(IBAction)playback{    player = [[AVAudioPlayer alloc]initWithContentsOfURL:temporaryRecfile error:nil];    //player.volume = 1;    [player setVolume: 1.0];    [player play];}-(IBAction)upload{    NSLog(@"upload");    recStateLabel.text = @"Uploading";    NSData *data = [NSData dataWithContentsOffile:NstemporaryDirectory()];    NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@""];    [urlString appendFormat:@"%@",data];    NSData *postData = [urlString dataUsingEnCoding:NSASCIIStringEnCoding                               allowLossyConversion:YES];    Nsstring *postLength = [Nsstring stringWithFormat:@"%d",[postData length]];    Nsstring *baseurl = @"http://efron.org.il/dev/singsong/upload.PHP";    NSURL *url = [NSURL URLWithString:baseurl];    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];    [urlRequest sethttpMethod: @"POST"];    [urlRequest setValue:postLength forhttpheaderFIEld:@"Content-Length"];    [urlRequest setValue:@"application/x-www-form-urlencoded"      forhttpheaderFIEld:@"Content-Type"];    [urlRequest sethttpBody:postData];    NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];    [connection start];    NSLog(@"Started!");    /*    SThttpRequest *r = [SThttpRequest requestWithURLString:@"http://efron.org.il/dev/singsong/upload.PHP"];    r.completionBlock = ^(NSDictionary *headers,Nsstring *body) {        // ...    };    r.errorBlock = ^(NSError *error) {        NSLog(@"error");    };    [r setfileToUpload:NstemporaryDirectory() parametername:@"sound"];    [r startAsynchronous];    ///..................///    Nsstring *boundary = @"---------------------------14737809831466499882746641449";    NSMutableData *postData = [NSMutableData data];    Nsstring *header = [Nsstring stringWithFormat:@"--%@\r\n",boundary];    [postData appendData:[header dataUsingEnCoding:NSUTF8StringEnCoding]];    //add your filename entry    Nsstring *contentdisposition = [Nsstring stringWithFormat:@"Content-disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"filename",@"iosaudio"];    [postData appendData:[contentdisposition dataUsingEnCoding:NSUTF8StringEnCoding]];    [postData appendData:[NSData dataWithContentsOffile:NstemporaryDirectory()]];    Nsstring *endItemBoundary = [Nsstring stringWithFormat:@"\r\n--%@\r\n",boundary];    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];    [request sethttpMethod:@"POST"];    [request setURL:[NSURL URLWithString:@"http://efron.org.il/dev/singsong/upload.PHP"]];    [postData appendData:[endItemBoundary dataUsingEnCoding:NSUTF8StringEnCoding]];    [request sethttpBody:postData];    ///...........///    NSURL *url = [NSURL URLWithString:@"http://efron.org.il/"];    AFhttpClIEnt *httpClIEnt = [[AFhttpClIEnt alloc] initWithBaseURL:url];    NSData *songData = [NSData dataWithContentsOfURL:temporaryRecfile];    NSMutableURLRequest *request = [httpClIEnt multipartFormRequestWithMethod:@"POST" path:@"dev/singsong/upload.PHP" parameters:nil constructingBodyWithBlock: ^(ID <AFMultipartFormData>formData) {        [formData appendPartWithFormData:songData name:@"file"];    }];    AFhttpRequestoperation *operation = [[AFhttpRequestoperation alloc] initWithRequest:request];    [operation setUploadProgressBlock:^(NSUInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) {        recStateLabel.text = [Nsstring stringWithFormat:@"Sent %lld/%lld",totalBytesWritten,totalBytesExpectedToWrite];    }];    [httpClIEnt enqueuehttpRequestoperation:operation];     */}- (voID)vIEwDIDLoad{    isNotRecording = YES;    playbutton.hIDden = YES;    recStateLabel.text = @"Not Recording";    AVAudioSession *audioSession = [AVAudioSession sharedInstance];    [audioSession setcategory:AVAudioSessioncategoryPlayAndRecord error:nil];    [audioSession setActive:YES error:nil];    [super vIEwDIDLoad];    // Do any additional setup after loading the vIEw,typically from a nib.}- (voID)dIDReceiveMemoryWarning{    [super dIDReceiveMemoryWarning];    // dispose of any resources that can be recreated.}@end

VIEwController.m包含了我对STHTTPRequest和AFNetworking等库进行的一些测试

解决方法 这行代码对我很有用

现在我发布了我的整个代码用于记录,保存,播放和放大发布到服务器

编辑: –

SoundRecordVC.h

///***********************  SoundRecordVC.h   ***************************//#import <UIKit/UIKit.h>#import <AVFoundation/AVFoundation.h>@interface SoundRecordVC : UIVIEwController<AVAudioPlayerDelegate,AVAudioRecorderDelegate>{    BOol stopBtnFlag;    BOol pauseBtnFlag;    NSTimer *timer;    AVAudioPlayer *audioPlayer;    AVAudioRecorder *audioRecorder;}    // ------------------- PropertIEs ---------------------@property (weak,nonatomic) IBOutlet UIbutton *recordBtn;@property (weak,nonatomic) IBOutlet UIbutton *playBtn;@property (strong,nonatomic) AVAudioRecorder *audioRecorder;@property (strong,nonatomic) AVAudioPlayer *audioPlayer;@property (strong,nonatomic) Nsstring *frIEndID;    // ------------------- IBAction ------------------ (IBAction)recordBtnpressed:(ID)sender;- (IBAction)playBtnpressed:(ID)sender;

SoundRecordVC.m

//***********************  SoundRecordVC.m   ***************************//#import "SoundRecordVC.h"@interface SoundRecordVC.m ()@end@implementation SoundRecordVC.m@synthesize recordBtn;@synthesize playBtn;- (ID)initWithNibname:(Nsstring *)nibnameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibname:nibnameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization    }    return self;}- (voID)vIEwDIDLoad{    [super vIEwDIDLoad];}#pragma mark -#pragma mark - methods- (IBAction)recordBtnpressed:(ID)sender{    if (!stopBtnFlag)    {        if (!audioRecorder.recording)        {            [self performSelectorOnMainThread:@selector(setUpAudioRecorder) withObject:nil waitUntilDone:YES];            [audioRecorder record];             NSLog(@"Recording...");        }        stopBtnFlag = YES;    }    else    {        [audioRecorder stop];        stopBtnFlag = NO;      }}-(voID)setUpAudioRecorder{    AVAudioSession *audioSession = [AVAudioSession sharedInstance];    [audioSession setcategory:AVAudioSessioncategoryRecord error:nil];    // --------------------- Setting for audio ----------------------//    NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:AVAudioQualityMedium],[NSNumber numberWithInt:2],[NSNumber numberWithInt:44100.0],nil];    NSError *error = nil;    // --------------------- file save Path ----------------------//    NSArray *paths = NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,NSUserDomainMask,YES);    Nsstring *documentsDirectory = [paths objectAtIndex:0];    NSURL *url = [NSURL fileURLWithPath:[Nsstring stringWithFormat:@"%@/sounds.caf",documentsDirectory]];    audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];    audioRecorder.delegate = self;    if ([audioRecorder preparetoRecord] == YES){        [audioRecorder preparetoRecord];    }else {        int errorCode = CFSwAPInt32HostToBig ([error code]);        NSLog(@"Error: %@ [%4.4s])",[error localizedDescription],(char*)&errorCode);    }}- (IBAction)playBtnpressed:(ID)sender {    AVAudioSession *audioSession = [AVAudioSession sharedInstance];    [audioSession setcategory:AVAudioSessioncategoryPlayback error:nil];    //----------------------loading files to player for playing------------------------------------//    NSArray *paths = NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,documentsDirectory]];    NSError *error;    NSLog(@"url is %@",url);    [audioPlayer stop];    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];    audioPlayer.numberOfLoops = 0;    audioPlayer.delegate=self;    [audioPlayer preparetoPlay];    if(!pauseBtnFlag){        NSLog(@"Playing.......");        [audioPlayer play];         pauseBtnFlag=YES;    }else{         NSLog(@"Pause");        [audioPlayer pause];        pauseBtnFlag=NO;    }}#pragma mark - #pragma mark - AVRecorder Delegate-(voID)audioRecorderDIDFinishRecording: (AVAudioRecorder *)recorder successfully:(BOol)flag{    NSLog (@"audioRecorderDIDFinishRecording:successfully");    NSLog(@"Stopped");}-(voID)audioRecorderEncodeErrorDIDOccur:(AVAudioRecorder *)recorder error:(NSError *)error{    NSLog(@"Encode Error occurred");}-(voID)audioPlayerDIDFinishPlaying:(AVAudioPlayer *)player successfully:(BOol)flag{}-(voID)dataUploadOnServer        {             NSLog(@"upload");                recStateLabel.text = @"Uploading";                Nsstring *baseurl = @"http://efron.org.il/dev/singsong/upload.PHP";                NSURL *dataURL = [NSURL URLWithString:baseurl];                    NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];                        [dataRqst sethttpMethod:@"POST"];                        Nsstring *stringBoundary = @"0xKHTMLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";                        Nsstring *headerBoundary = [Nsstring stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];                        [dataRqst addValue:headerBoundary forhttpheaderFIEld:@"Content-Type"];                        NSMutableData *postbody = [NSMutableData data];                        // -------------------- ---- Audio Upload Status ---------------------------\                        //pass MediaType file                        [postbody appendData:[[Nsstring stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEnCoding:NSUTF8StringEnCoding]];                        [postbody appendData:[@"Content-disposition: form-data; name=\"Data\"; filename=\"myVoice.mp3\"\r\n" dataUsingEnCoding:NSUTF8StringEnCoding]];                        [postbody appendData:[@"Content-Type: audio/caf\r\n" dataUsingEnCoding:NSUTF8StringEnCoding]];                        [postbody appendData:[@"Content-transfer-encoding: binary\r\n\r\n" dataUsingEnCoding:NSUTF8StringEnCoding]];                        //*******************load locally store audio file********************//                        NSArray *paths = NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,YES);                        Nsstring *documentsDirectory = [paths objectAtIndex:0];                        Nsstring *audioUrl = [Nsstring stringWithFormat:@"%@/record.mp3",documentsDirectory];                         // get the audio data from main bundle directly into NSData object                        NSData *audioData;                        audioData = [[NSData alloc] initWithContentsOffile:audioUrl];                        // add it to body                        [postbody appendData:audioData];                        [postbody appendData:[@"\r\n" dataUsingEnCoding:NSUTF8StringEnCoding]];                        // final boundary                        [postbody appendData:[[Nsstring stringWithFormat:@"--%@--\r\n",stringBoundary] dataUsingEnCoding:NSUTF8StringEnCoding]];                        // add body to post                        [dataRqst sethttpBody:postbody];                        NShttpURLResponse* response =[[NShttpURLResponse alloc] init];                        NSError* error = [[NSError alloc] init] ;                        //synchronous filling of data from http POST response                        NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRqst returningResponse:&response error:&error];                        //convert data into string                        Nsstring *responseString = [[Nsstring alloc] initWithBytes:[responseData bytes] length:[responseData length] enCoding:NSUTF8StringEnCoding];                        NSLog(@"Response String %@",responseString);}#pragma mark -- (voID)dIDReceiveMemoryWarning{    [super dIDReceiveMemoryWarning];    // dispose of any resources that can be recreated.}- (voID)vIEwDIDUnload{    [self setPlayBtn:nil];    [super vIEwDIDUnload];}

@结束

我希望它对你有用

总结

以上是内存溢出为你收集整理的将AVAudioRecorder发送到服务器iOS全部内容,希望文章能够帮你解决将AVAudioRecorder发送到服务器iOS所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1071746.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存