音频录制上传服务器,调用系统相机

时间:2022-09-29 11:20:10
调用系统相机,实现音频录制,音频上传服务器,这是原始代码,后期会做一定的调整。但是基本功能都已实现,仅供诸位参考,最近有点忙,但是尽快修正

#import <AFNetworking.h>

#import <AVFoundation/AVFoundation.h>



@property(nonatomic,strong)AVAudioRecorder*audioRecorder;
@property(nonatomic,strong)AVAudioPlayer*audioPlayer;
@property(nonatomic,retain)NSDictionary*recordSetting;



@property(nonatomic,strong)NSData*data;
@property(nonatomic,copy)NSString*dataStr;
//配置recorder  因为录音机必须知道录音文件的格式、采样率、通道数、每个采样点的位数等信息     /*AVEncoderAudioQualityKey音质,
     AVEncoderBitRateKey
编码器 比特率
     AVNumberOfChannelsKey
设置通道
     AVSampleRateKey 
设置录音采样率
     */

   
self.recordSetting= [NSDictionarydictionaryWithObjectsAndKeys:
                          [
NSNumbernumberWithInt:AVAudioQualityLow],AVEncoderAudioQualityKey,[NSNumbernumberWithInt:16],AVEncoderBitRateKey,
                          [
NSNumbernumberWithInt:2],AVNumberOfChannelsKey,
                          [NSNumbernumberWithFloat:44100.0],AVSampleRateKey,nil];
//开始录音
- (
void)recordButtonAction{
   
//判断是否正在录音;
   
if (self.audioRecorder.recording== 0) {
        [
self.audioRecorderrecord];//开始录音
       
NSLog(@"开始录音");
    }
else{
        [
self.audioRecorderstop];//停止录音  stops recording. closes the file. 停止记录。关闭文件。
       
NSLog(@"结束录音");

       
NSData *data = [NSDatadataWithContentsOfFile:_dataStr];
        _data = data;
       
    }
}
-(void)openVidio{
   
   
if (!self.audioPlayer.playing) {
       
NSError *error;
       
//录音文件存储的路径
       
NSLog(@"self.audioRecorder.url = %@",self.audioRecorder.url);
       
//初始化AVAudioPlayer *audioPlayer;
       
self.audioPlayer= [[AVAudioPlayeralloc]initWithContentsOfURL:self.audioRecorder.urlerror:&error];
       
//设置代理
       
self.audioPlayer.delegate= self;
       
_timer = [NSTimerscheduledTimerWithTimeInterval:1.0target:selfselector:@selector(openTimer)userInfo:nilrepeats:nil];
       
if (error != nil) {
           
NSLog(@"player错误:%@",error);
        }
else{
           
//icon_record;
            [
_vedioBtnsetImage:[UIImageimageNamed:@"icon_record"]forState:UIControlStateNormal];
            [
_vedioBtnsetTitle:@"正在播放"forState:UIControlStateNormal];
            [
self.audioPlayerplay];//播放录音
           
        }
       
    }
else{
//        self.recordButton.hidden = NO;//录音按钮显示
        [
self.audioPlayerpause];//暂停播放,
       
    }

   
}
-(void)didReceived{
//   音频上传;
//    NSLog(@"%@",_data);
   
NSMutableDictionary *parameter = [[NSMutableDictionaryalloc]init];
    [parameter
setObject:_dataforKey:@"voice"];
    [parameter
setObject:@"1"forKey:@"babyid"];
    [parameter
setObject:@"1"forKey:@"id"];
   
   
AFHTTPSessionManager *manager = [AFHTTPSessionManagermanager];
    [manager.
responseSerializersetAcceptableContentTypes:[NSSetsetWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/css",@"text/plain",nil]];
   
NSString *imageUrl =@"http://192.168.1.107/demo/index.php/home/addcontents/uploadvoice";
   
    [manager
POST:imageUrl parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData_NonnullformData) {
       
NSDateFormatter *formatter = [[NSDateFormatteralloc]init]; formatter.dateFormat= @"yyyyMMddHHmmss";
       
NSString *str = [formatterstringFromDate:[NSDatedate]];//fileName这里取当前时间戳
       
NSString *fileName = [NSStringstringWithFormat:@"%@.amr", str];
        [formData
appendPartWithFileData:_dataname:@"voice"fileName:fileNamemimeType:@"wav/mp3/wmr"];
       
    }
progress:^(NSProgress* _Nonnull uploadProgress) {
       
    }
success:^(NSURLSessionDataTask* _Nonnull task, id  _Nullable responseObject) {
       
NSLog(@"%@",responseObject);
    }
failure:^(NSURLSessionDataTask* _Nullable task,NSError* _Nonnull error) {
            }];     [self.navigationControllerpopViewControllerAnimated:YES];
   
}
-(AVAudioRecorder*)audioRecorder{
   
   
if (!_audioRecorder) {
       
//录音文件要选用document路径,否则真机运行会出错误;
       
       
       
//NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recorder.caf",[[NSBundle mainBundle] resourcePath]]];错误地址;
       
       
       
NSString *urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
        urlStr=[urlStr
stringByAppendingPathComponent:@"/recorder.wav"];
       
_dataStr = urlStr;
       
       
NSLog(@"file path:%@",urlStr);
       
NSURL *url=[NSURLfileURLWithPath:urlStr];
       
NSError *errol =nil;
       
AVAudioSession *session = [AVAudioSessionsharedInstance];
       
NSError *setCategoryError =nil;
        [session
setCategory:AVAudioSessionCategoryPlayAndRecorderror:&setCategoryError];
       
       
if(setCategoryError){
           
NSLog(@"%@", [setCategoryErrordescription]);
        }
       
       
//初始化AVAudioRecorder *audioRecorder
       
self.audioRecorder= [[AVAudioRecorderalloc]initWithURL:urlsettings:self.recordSettingerror:&errol];
       
       
       
if (errol != nil) {
           
NSLog(@"创建录音机对象时发生错误,错误信息:%@",errol);
           
NSLog(@"出错了");
           
        }
else{
           
//准备就绪,等待录音该方法会返回Boolean,做个判断,有错误可以抛出异常信息
           
//prepareToRecord  创建文件,准备记录。会自动记录
           
if ([self.audioRecorderprepareToRecord]) {
               
NSLog(@"成功,准备就绪,等待录音");
            }
        }
       
    }

    return _audioRecorder;
   
}
//当声音文件播放结束时,需要通知主程序,需要使用AVAudioPlayerDelegate,也可以实现AVAudioRecorderDelegate刈记录record的状态
#pragma mark AVAudioPlayerDelegate
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
   
NSLog(@"完成播放");
   
    [
self.tableViewreloadData];
   
}

-(
void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError*)error{
   
NSLog(@"Decode Error occurred");//解码错误发生
}


#pragma mark AVAudioRecorderDelegate
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder*)recorder successfully:(BOOL)flag{
   
NSLog(@"完成record");//如果发生错误,而编码将报告委托
}

-(
void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder*)recorder error:(NSError*)error{
   
NSLog(@"Encode Error occurred");//录音编码发生错误
}


-(
void)viewWillAppear:(BOOL)animated{
    [
self.tableViewreloadData];
}
#pragma mark........UIImagePickerControllerDelegate.UINavigationControllerDelegate,调用系统相机

- (
void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
   
   
   
if (buttonIndex ==2)return;
   
UIImagePickerController *imagePicker = [[UIImagePickerControlleralloc]init];
    imagePicker.
allowsEditing= YES;
    imagePicker.
delegate= self;
   
if (buttonIndex ==1) {
        imagePicker.
sourceType= UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
else{
        imagePicker.
sourceType= UIImagePickerControllerSourceTypeCamera;
       
    }
    [
selfpresentViewController:imagePickeranimated:YEScompletion:nil];
}



//用户点击图像选取器中的“cancel”按钮时被调用,这说明用户想要中止选取图像的操作
- (
void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
{
    [picker
dismissViewControllerAnimated:YEScompletion:nil];
}

- (
void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString*,id> *)info
{
   
NSDictionary *dic = info;
   
UIImage *image = dic[UIImagePickerControllerOriginalImage];
   
   
_imageView.image= image;
    [
selfdismissViewControllerAnimated:YEScompletion:nil];
   
   
}