iOS為我們提供了AVFoundation FrameWork,即Audio/Video基礎類庫,通過使用這個類庫,可以在應用程式中實現錄製,播放視頻,音頻等功能,使用起來非常方便。
AVFoundation架構的作用
AVFoundation架構提供一系列的Class(類),在iPhone OS相關結構中,負責對象管理和播放視聽媒體,當引入此標頭檔後,便可以在程式裡使用任何在AVFoundation裡聲明的類:
#import <AVFoundation/AVAudionPlayer.h>
說明:AVAudioPlayer是iPhoneOS中的聲音播放器架構,使程式支援廣泛的音頻格式播放,格式包括AAC、AMR、ALAC、iLBC、IMA4、linearPCM和MP3等。
下面通過代碼的形式介紹AVAudioRecorder,AVAudioPlayer的基本使用。如有不足,還請大家多指點,以達到共同學習的目的!
廢話不多說,直接上代碼。
xib展示:
1.
2.
3.
說明:1圖和2圖中選中的兩個Button用於錄音時的動畫展示原理是:看圖,
底部一個Button,上面在疊加一個Button,兩個Button的backgroundImage為同一張圖片,但上層的Button大小較下面小一圈,通過調整底層Button的alpha達到動畫效果。
下面是該介面所需的代碼:
提示:添加AVFoundation架構並匯入
#import <AVFoundation/AVFoundation.h>#import "AddAttachmentsViewController.h"@interface SoundRecordingViewController () <AVAudioRecorderDelegate>{ NSTimer *_timer1; NSTimer *_timer2; NSString *_audioFilePath;}@property (nonatomic,assign)int minute, second, btnSeconds; //分,秒,秒數累加@property (weak, nonatomic) IBOutlet UIButton *animateBtn;@property (weak, nonatomic) IBOutlet UILabel *timeLabel;@property (nonatomic, strong) AVAudioRecorder *audioRecorder;@property (nonatomic, strong) AVAudioPlayer *audioPlayer;@property (nonatomic, strong) NSString *fileURL;@end@implementation SoundRecordingViewController- (void)viewDidLoad{ [super viewDidLoad]; [self setAudioSession];}#pragma mark - Outlet Aciton Event//按住開始錄音- (IBAction)clickToStartRecording:(UIButton *)sender{ _minute = 0; _second = 0; _btnSeconds = 0; _timeLabel.text = @"0:00"; if (_audioFilePath.length > 0) { NSError *error = nil; [[NSFileManager defaultManager] removeItemAtPath:_audioFilePath error:&error]; } if (![self.audioRecorder isRecording]) { [self.audioRecorder prepareToRecord]; //首次使用應用時如果調用record方法會詢問使用者是否允許使用麥克風 [self.audioRecorder record]; } [_timer1 invalidate]; _timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startAnimate) userInfo:nil repeats:YES]; [_timer2 invalidate]; _timer2 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTimeLabel) userInfo:nil repeats:YES];}//鬆開停止錄音- (IBAction)clickToStopRecording:(UIButton *)sender{ [self.audioRecorder stop]; [_timer1 invalidate]; [_timer2 invalidate]; _animateBtn.transform = CGAffineTransformMakeScale(1, 1);}- (void)startAnimate{ static BOOL alpha = YES; [UIView animateWithDuration:1.0f animations:^{ _animateBtn.alpha = alpha; }]; alpha = !alpha;}-(void)changeTimeLabel{ if(_second < 60) { //秒 _second ++; } else if(_second == 60) { //分 _second = 0; _minute++; } if (_second < 10) { _timeLabel.text = [NSString stringWithFormat:@"%d:0%d",_minute,_second]; }else{ _timeLabel.text = [NSString stringWithFormat:@"%d:%d",_minute,_second]; } _btnSeconds ++;}//設定音頻會話- (void)setAudioSession{ AVAudioSession *audioSession = [AVAudioSession sharedInstance]; //設定為播放和錄音狀態,以便可以在錄製完之後播放錄音 [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; [audioSession setActive:YES error:nil];}//擷取錄音檔案設定- (NSDictionary *)getAudioSetting{ NSMutableDictionary *recordSetting = [NSMutableDictionary dictionary]; //設定錄音格式 [recordSetting setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey]; //設定錄音採樣率,8000是電話採樣率,對於一般錄音已經夠用了 [recordSetting setObject:@(8000) forKey:AVSampleRateKey]; //設定通道為單聲道 [recordSetting setObject:@(2) forKey:AVNumberOfChannelsKey]; //每個採樣點位元,分為8,16,24,32 [recordSetting setObject:@(8) forKey:AVLinearPCMBitDepthKey]; //是否使用浮點數採樣 [recordSetting setObject:@(YES) forKey:AVLinearPCMIsFloatKey]; return recordSetting;}//重寫get:錄音機對象- (AVAudioRecorder *)audioRecorder{ if (!_audioRecorder) { _audioFilePath = [self getSavePathWithFileSuffix:@"caf"]; //錄音檔案儲存路徑 _fileURL = [NSURL fileURLWithPath:_audioFilePath]; //錄音格式設定 NSDictionary *setting = [self getAudioSetting]; //建立錄音機 NSError *error = nil; _audioRecorder = [[AVAudioRecorder alloc] initWithURL:_fileURL settings:setting error:&error]; if (error) { NSLog(@"建立錄音機失敗,錯誤資訊:%@",error); return nil; } } return _audioRecorder;}//播放本地音頻檔案的觸發時間,可以添加按鈕或其他來觸發播放- (void)playAudioFiles{ _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_fileURL error:&error]; if (error == nil) { _audioPlayer.currentTime = 0; [_audioPlayer play]; }} //擷取檔案名稱:由時間+尾碼組成+ (NSString *)getSavePathWithFileSuffix:(NSString *)suffix{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentPath = [paths objectAtIndex:0]; NSDate *date = [NSDate date]; //擷取目前時間 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyyMMddHHmmss"]; NSString *curretDateAndTime = [dateFormat stringFromDate:date]; //命名檔案 NSString *fileName = [NSString stringWithFormat:@"%@.%@",curretDateAndTime,suffix]; //指定檔案儲存體路徑 NSString *filePath = [documentPath stringByAppendingPathComponent:fileName]; return filePath;}