iOS录音及播放全解
生活随笔
收集整理的這篇文章主要介紹了
iOS录音及播放全解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
iOS錄音及播放全解
// // ViewController.m // 錄音與播放 // // Created by 張璟冰 on 2020/3/29. // Copyright ? 2020 張璟冰. All rights reserved. //#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController ()<AVAudioRecorderDelegate>{UILabel *timeLabel;float time;//保存我們錄音錄了多久 } @property(nonatomic,strong)AVAudioRecorder *audioRecorder;//錄音器 @property (nonatomic,strong) NSString *mp3Path; @property (nonatomic,strong) NSString *cafPath; @property (nonatomic, strong) NSTimer *timer;//定時器 @property (nonatomic, strong) AVAudioPlayer *player; //播放器 @end@implementation ViewController #pragma mark 第三步 錄音器的懶加載 - (AVAudioRecorder *)audioRecorder {if (!_audioRecorder){//7.0第一次運行會提示,是否允許使用麥克風AVAudioSession *session = [AVAudioSession sharedInstance];NSError *sessionError;//AVAudioSessionCategoryPlayAndRecord用于錄音和播放[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];if(session == nil)NSLog(@"Error creating session: %@", [sessionError description]);else[session setActive:YES error:nil];//創建錄音文件保存路徑NSURL *url = [self getSavePath];//創建錄音格式設置NSDictionary *setting = [self getAudioSetting];//創建錄音機NSError *error=nil;_audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];_audioRecorder.delegate=self;_audioRecorder.meteringEnabled=YES;//如果要監控聲波則必須設置為YES[_audioRecorder prepareToRecord];if (error){NSLog(@"創建錄音機對象時發生錯誤,錯誤信息:%@",error.localizedDescription);return nil;}}return _audioRecorder; } /*** 取得錄音文件保存路徑** @return 錄音文件路徑*/ -(NSURL *)getSavePath {//iPhone會為每一個應用程序生成一個私有目錄,這個目錄位于/user/.../Application下//并會隨機生成一個數字字母串作為目錄名//通常使用Documents目錄進行數據持久化的保存// 在Documents目錄下創建一個名為AudioData的文件夾、NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioData"];NSLog(@"%@",path);NSFileManager *fileManager = [NSFileManager defaultManager];BOOL isDir = FALSE;BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];if(!(isDirExist && isDir)){BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];if(!bCreateDir){NSLog(@"創建文件夾失敗!");}NSLog(@"創建文件夾成功,文件路徑%@",path);}NSString *fileName = @"record";NSString *cafFileName = [NSString stringWithFormat:@"%@.caf", fileName];NSString *mp3FileName = [NSString stringWithFormat:@"%@.mp3", fileName];//拼接路徑NSString *cafPath = [path stringByAppendingPathComponent:cafFileName];NSString *mp3Path = [path stringByAppendingPathComponent:mp3FileName];self.mp3Path = mp3Path;self.cafPath = cafPath;NSLog(@"file path:%@",cafPath);NSURL *url=[NSURL fileURLWithPath:cafPath];return url; } /*** 取得錄音文件設置** @return 錄音設置*/ - (NSDictionary *)getAudioSetting {NSMutableDictionary *dicM = [NSMutableDictionary dictionary];[dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey]; // [dicM setObject:@(ETRECORD_RATE) forKey:AVSampleRateKey];[dicM setObject:@(2) forKey:AVNumberOfChannelsKey];[dicM setObject:@(16) forKey:AVLinearPCMBitDepthKey];[dicM setObject:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];return dicM; } - (void)viewDidLoad {[super viewDidLoad];UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];btn.tag = 10000;[btn setTitle:@"開始錄音" forState:UIControlStateNormal];[btn setTitle:@"停止錄音" forState:UIControlStateSelected];[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];btn.backgroundColor = [UIColor whiteColor];[btn addTarget:self action:@selector(recordClick:) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:btn];UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(120, 0, 100, 100)];btn2.tag = 10001;[btn2 setTitle:@"播放錄音" forState:UIControlStateNormal];[btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];btn2.backgroundColor = [UIColor whiteColor];[btn2 addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:btn2];//時間timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, 100, 30)];timeLabel.text = @"錄音時長";timeLabel.font = [UIFont systemFontOfSize:16];timeLabel.textColor = [UIColor blackColor];[self.view addSubview:timeLabel]; } #pragma mark 播放錄音 -(void)play:(UIButton *)sender {if ([self.player isPlaying])return;self.player = [[AVAudioPlayer alloc]initWithData:[NSData dataWithContentsOfFile:self.cafPath] error:nil];[self.player play]; } #pragma mark 第四步 開始/結束錄音點擊、播放點擊 -(void)recordClick:(UIButton *)sender {sender.selected = !sender.selected;if (sender.selected){//開始錄音[self startRecord];}else{//結束錄音[self finishRecorded];} } //結束錄音 - (void)finishRecorded {//使用系統自帶錄音機if ([self.audioRecorder isRecording]){NSLog(@"完成");[self destoryTimer];[self.audioRecorder stop];//停止工作}if (time < 1){NSLog(@"錄音時間過短!");//清空錄音內容return;}//進行錄音格式的轉碼成mp3格式、提交網絡上傳//Lametime = 0;timeLabel.text = @"點擊錄音";} //開始錄音 - (void)startRecord {// 重置錄音機if (self.audioRecorder){self.audioRecorder = nil;time = 0;[self destoryTimer];}if (![self.audioRecorder isRecording]){AVAudioSession *session = [AVAudioSession sharedInstance];NSError *sessionError;//AVAudioSessionCategoryPlayAndRecord用于錄音和播放[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];if(session == nil)NSLog(@"Error creating session: %@", [sessionError description]);else[session setActive:YES error:nil];//創建定時器方法,實時計算錄音了幾秒鐘self.timer = [NSTimer scheduledTimerWithTimeInterval:1target:selfselector:@selector(record)userInfo:nilrepeats:YES];timeLabel.text = @"00:00";[self.audioRecorder record];//開始工作NSLog(@"錄音開始");}else{NSLog(@"is recording now ....");}} // 定時器方法--錄音時間計算 - (void)record {time = time+1;timeLabel.text = [self timeFormatted:(float)time];//假如一次性只能錄180s,一般寫倒計時提示if (time == 180){NSLog(@"%@",@"最多僅能錄取180s");//結束錄音UIButton *btn = [self.view viewWithTag:10000];btn.selected = !btn.selected; // [self finishRecorded];//調用錄音結束[self.timer invalidate];self.timer = nil; // _recordGIFImg.hidden = YES;//關閉GIF圖,這個圖是一個光播圖標))) // [_recordGIFImg stopAnimating];} } - (NSString *)timeFormatted:(NSInteger)totalSeconds {NSInteger seconds = totalSeconds % 60;NSInteger minutes = (totalSeconds / 60) % 60;NSInteger hours = totalSeconds / 3600;if (hours <= 0){return [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes, (long)seconds];}return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hours, (long)minutes, (long)seconds]; }//銷毀定時器 - (void)destoryTimer {if (self.timer){[self.timer invalidate];//使其無效self.timer = nil;//置空NSLog(@"----- timer destory");} } @end總結
以上是生活随笔為你收集整理的iOS录音及播放全解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Altium Designer2018
- 下一篇: 使用idea 把项目上传到 svn