iOS 保存錄音
阿新 • • 發佈:2018-11-05
-(void)testClick{ [_recorder record]; [self performSelector:@selector(stopRecorder) withObject:nil afterDelay:15]; } -(void)stopRecorder{ [_recorder stop]; // NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"tmp/aaa"]; // NSURL* url = [NSURL fileURLWithPath:path]; // NSData *data = [NSData dataWithContentsOfURL:url]; // [data writeToFile:[NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp/aaa"] atomically:YES]; NSLog(@"voicerecorder stop"); } -(void)configRecorder{ //設定音訊會話 NSError *sessionError; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&sessionError]; if (sessionError){ NSLog(@"Error creating session: %@",[sessionError description]); }else{ [[AVAudioSession sharedInstance] setActive:YES error:&sessionError]; } NSError *error = nil; NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init]; [recordSetting setObject:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey]; [recordSetting setObject:[NSNumber numberWithFloat:22050] forKey:AVSampleRateKey]; [recordSetting setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey]; [recordSetting setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; //是否使用浮點數取樣 [recordSetting setObject:@(YES) forKey:AVLinearPCMIsFloatKey]; [recordSetting setObject:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey]; NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"aaa.wav"]; NSURL* url = [NSURL fileURLWithPath:path]; _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil]; _recorder.meteringEnabled = YES; [_recorder prepareToRecord]; }
溫馨提示:AVFormatIDKey 涉及到編碼方式,又幾十種列舉值,經他人試過幾種後,kAudioFormatLinearPCM會編碼成wav編碼格式,這種格式蘋果和安卓都可以直接播放,親測