这两天看了一下IOS的录音,,,参考了一下前辈们的帖子,点击打开链接
IOS的录音主要依靠AVFoundation.framework与CoreAudio.framework两个框架来实现。
工程里添加这两个框架。
#import "textViewController.h"
#import "RootViewController.h"
@interface textViewController (){
NSURL *recordedTmpFile;
AVAudioRecorder *recorder;
NSError *error;
BOOL toggle;
BOOL isPlaying;
AVAudioPlayer *avPlayer;
UIAlertView *customAlert;
NSInteger time;
NSTimer *timer;
NSMutableArray *myArray;
}
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITextField *volume;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *luyinButton;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityView;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@implementation textViewController
- (NSString *)dataFilePath:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folderPath = [paths objectAtIndex:0];
return [folderPath stringByAppendingPathComponent:name];
}
- (NSString *)dataFilePathMP3:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folderPath = [[paths objectAtIndex:0]stringByAppendingString:@"MP3/"];
return [folderPath stringByAppendingPathComponent:name];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSError *errorr;
toggle = YES;
isPlaying = NO;
self.activityView.hidden = YES;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&errorr];
[audioSession setActive:YES error:&errorr];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
[timer setFireDate:[NSDate distantFuture]];
NSString *recordListPath = [self dataFilePath:@"recordList.plist"];
if ([[NSFileManager defaultManager]fileExistsAtPath:recordListPath]) {
myArray = [NSMutableArray arrayWithContentsOfFile:recordListPath];
}else{
myArray = [NSMutableArray arrayWithCapacity:0];
}
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)luyin:(id)sender {
if (toggle) {
toggle = NO;
NSError *error0;
self.activityView.hidden = NO;
[self.activityView startAnimating];
[self.luyinButton setTitle:@"停止录音" forState:UIControlStateNormal];
[timer setFireDate:[NSDate distantPast]];
time = 0;
//录音设置
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
//录音格式
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
//采样率:11025.0
[recordSetting setValue:[NSNumber numberWithFloat:[self.textField.text floatValue]] forKey:AVSampleRateKey];
//通道数
[recordSetting setValue:[NSNumber numberWithInt:[self.volume.text intValue]] forKey:AVNumberOfChannelsKey];
//线性采样位数
[recordSetting setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
//音频质量,采样质量
[recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:@"yyyy_MM_dd_hh_mm_ss"]; //yyyy-MM-dd hh:mm:ss
NSString *showtimeNew = [formatter1 stringFromDate:[NSDate date]];
recordedTmpFile = [NSURL fileURLWithPath:[self dataFilePathMP3:[NSString stringWithFormat: @"%@.caf", showtimeNew]]];
[[NSUserDefaults standardUserDefaults]setObject:showtimeNew forKey:@"name"];
NSLog(@"using file called:%@",recordedTmpFile);
recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error0];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
}else{
toggle = YES;
self.activityView.hidden = YES;
[self.activityView stopAnimating];
[self.luyinButton setTitle:@"开始录音" forState:UIControlStateNormal];
[recorder stop];
[timer setFireDate:[NSDate distantFuture]];
[[NSUserDefaults standardUserDefaults]setObject:self.timeLabel.text forKey:@"time"];
customAlert= [[UIAlertView alloc]initWithTitle:@"请为您的录音文件命名加以保存" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存", nil];
customAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField *textField = [customAlert textFieldAtIndex:0];
textField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
[customAlert show];
}
}
- (IBAction)play:(id)sender {
NSError *error11;
if (isPlaying) {
isPlaying = NO;
[self.playButton setTitle:@"开始播放" forState:UIControlStateNormal];
[avPlayer stop];
}else{
isPlaying = YES;
[self.playButton setTitle:@"停止播放" forState:UIControlStateNormal];
NSLog(@"recordTmpFile---%@",recordedTmpFile);
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:recordedTmpFile error:&error11];
[avPlayer prepareToPlay];
[avPlayer play];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
[alertView dismissWithClickedButtonIndex:0 animated:YES];
NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
[[NSFileManager defaultManager]removeItemAtPath:[self dataFilePathMP3:[NSString stringWithFormat:@"%@.caf",name]] error:nil];
}else if (buttonIndex==1){
UITextField *textField = [customAlert textFieldAtIndex:0];
NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
if ([[NSFileManager defaultManager]fileExistsAtPath:[self dataFilePathMP3:[NSString stringWithFormat:@"%@.caf",name]]]) {
[[NSFileManager defaultManager]moveItemAtPath:[self dataFilePathMP3:[NSString stringWithFormat:@"%@.caf",name]] toPath:[self dataFilePath:[NSString stringWithFormat:@"%@",textField.text]] error:nil];
}
NSString *recordListPath = [self dataFilePath:@"recordList.plist"];
NSMutableArray *recordArray;
if ([[NSFileManager defaultManager]fileExistsAtPath:recordListPath]) {
recordArray = [NSMutableArray arrayWithContentsOfFile:recordListPath];
}else{
recordArray = [NSMutableArray arrayWithCapacity:0];
}
if (![recordArray containsObject:textField.text]) {
[recordArray addObject:textField.text];
}
[recordArray writeToFile:[self dataFilePath:@"recordList.plist"] atomically:YES];
myArray = [NSMutableArray arrayWithArray:recordArray];
[self.myTableView reloadData];
}
}
-(void)updateTime{
time = time+1;
self.timeLabel.hidden = NO;
if(time>=3600){
self.timeLabel.text=[NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)time/3600,(long)(time%3600)/60,(long)time%60];
}else{
self.timeLabel.text=[NSString stringWithFormat:@"%02d:%02ld:%02ld",0,(long)time/60,(long)time%60];
}
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [myArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [myArray objectAtIndex:row];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 50;
}
不过,我遇到一个问题,录音没问题,保存的文件都能找见,用电脑播放录音文件也没问题,但是用手机去播放录音文件就听不见声音,我怀疑是声音特别小才导致的听不见。。。不知道是不是 ,怎么样才能解决这种问题呢?