iOS 實現(xiàn)錄音功能

參考資料

http://www.itdecent.cn/p/fb7dfb033989

音頻文件相關(guān)知識

文件格式
wav:
特點:音質(zhì)最好的格式,對應(yīng)PCM編碼
適用:多媒體開發(fā),保存音樂和音效素材
mp3:
特點:音質(zhì)好,壓縮比比較高,被大量軟件和硬件支持
適用:適合用于比較高要求的音樂欣賞
caf:
特點:適用于幾乎iOS中所有的編碼格式
編碼格式
PCM
PCM:脈沖編碼調(diào)制,是一種非壓縮音頻數(shù)字化技術(shù),是一種未壓縮的原音重現(xiàn),數(shù)字模式下,音頻的初始化信號是PCM
MP3
AAC
AAC:其實是“高級音頻編碼(advanced audio coding)”的縮寫,他是被設(shè)計用來取代MPC格式的。
HE-AAC
HE-AAC是AAC的一個超集,這個“High efficiency”,HE-AAC是專門為低比特率所優(yōu)化的一種音頻編碼格式。
AMR
AMR全稱是“Adaptive Multi-Rate”,它也是另一個專門為“說話(speech)”所優(yōu)化的編碼格式,也是適合低比特率環(huán)境下采用。
ALAC
它全稱是“Apple Lossless”,這是一種沒有任何質(zhì)量損失的音頻編碼方式,也就是我們說的無損壓縮。
IMA4
IMA4:這是一個在16-bit音頻文件下按照4:1的壓縮比來進(jìn)行壓縮的格式。
影響音頻文件大小的因素
采樣頻率
采樣頻率是指單位時間內(nèi)的采樣次數(shù)。采樣頻率越大,采樣點之間的間隔就越小,數(shù)字化后得到的聲音就越逼真,但相應(yīng)的數(shù)據(jù)量就越大。
采樣位數(shù)
采樣位數(shù)是記錄每次采樣值數(shù)值大小的位數(shù)。采樣位數(shù)通常有8bits或16bits兩種,采樣位數(shù)越大,所能記錄聲音的變化度就越細(xì)膩,相應(yīng)的數(shù)據(jù)量就越大。
聲道數(shù)
聲道數(shù)是指處理的聲音是單聲道還是立體聲。單聲道在聲音處理過程中只有單數(shù)據(jù)流,而立體聲則需要左、右聲道的兩個數(shù)據(jù)流。顯然,立體聲的效果要好,但相應(yīng)的數(shù)據(jù)量要比單聲道的數(shù)據(jù)量加倍。
時長
計算
數(shù)據(jù)量(字節(jié)/秒)=(采樣頻率(Hz)× 采樣位數(shù)(bit)× 聲道數(shù))/ 8
總大小=數(shù)據(jù)量 x 時長(秒)
設(shè)置申請訪問權(quán)限
申請訪問權(quán)限,在plist文件中加入
<key>NSMicrophoneUsageDescription</key> <string>App需要您的同意,才能訪問麥克風(fēng)</string>
實測音頻大小
錄音1分鐘:
caf格式用了2.6MB
mp3格式用了227KB 

錄音10分鐘:
caf格式用了26.5MB
mp3格式用了2.3MB 
caf轉(zhuǎn)mp3

參考我的這篇博客
http://www.itdecent.cn/p/62cac1ddb2a5

代碼實現(xiàn)

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>{
    
    AVAudioRecorder *recorder;
    AVAudioPlayer *player;
    /** 錄音計時器 */
    NSTimer *recordTimer;
    /** 播放計時器 */
    NSTimer *playTimer;
    /** 錄音時間 */
    NSInteger recordSecond;
    /** 錄音分鐘時間 */
    NSInteger minuteRecord;
    /** 播放時間 */
    NSInteger playSecond;
    /** 播放分鐘時間 */
    NSInteger minutePlay;
    /** caf文件路徑 */
    NSURL *tmpUrl;
}

/** 時間 */
@property (nonatomic, strong) UILabel *timeLbl;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createUI];
}

#pragma mark - 搭建界面
- (void)createUI{
    
    // 開始,這里自己創(chuàng)建UIButton
    UIButton *startBtn = [UIButton createButtonWithTitle:@"開始" sel:@selector(startBtnEvent:) vc:self];
    startBtn.frame = CGRectMake(100, 100, 200, 50);
    [self.view addSubview:startBtn];

    // 結(jié)束
    UIButton *endBtn = [UIButton createButtonWithTitle:@"結(jié)束" sel:@selector(endBtnEvent:) vc:self];
    endBtn.frame = CGRectMake(100, 150, 200, 50);
    [self.view addSubview:endBtn];

    // 播放
    UIButton *playBtn = [UIButton createButtonWithTitle:@"播放" sel:@selector(playBtnEvent:) vc:self];
    playBtn.frame = CGRectMake(100, 200, 200, 50);
    [self.view addSubview:playBtn];
    
    // 時間
    self.timeLbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 250, 200, 50)];
    self.timeLbl.textColor = [UIColor blackColor];
    self.timeLbl.textAlignment = NSTextAlignmentCenter;
    self.timeLbl.text = @"00:00";
    [self.view addSubview:self.timeLbl];
}


/**
 開始
 */
- (void)startBtnEvent:(UIButton *)btn{

    // 開始錄音
    [self recordingAction];
}


/**
 結(jié)束
 */
- (void)endBtnEvent:(UIButton *)btn{

    // 停止錄音
    [self stopAction];
}


/**
 播放
 */
- (void)playBtnEvent:(UIButton *)btn{

   // 播放錄音
   [self playAction];
}


/**
 開始錄音
 */
- (void)recordingAction {
    
    NSLog(@"開始錄音");
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

    //錄音設(shè)置
    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
    //錄音格式 
    [recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
    //采樣率
    [recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
    //通道數(shù)
    [recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //線性采樣位數(shù)
    [recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
    //音頻質(zhì)量,采樣質(zhì)量
    [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];

    NSError *error = nil;
    // 沙盒目錄Documents地址
    NSString *recordUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // caf文件路徑
    tmpUrl = [NSURL URLWithString:[recordUrl stringByAppendingPathComponent:@"selfRecord.caf"]];
    recorder = [[AVAudioRecorder alloc]initWithURL:tmpUrl settings:recordSettings error:&error];
    
    if (recorder) {
        //啟動或者恢復(fù)記錄的錄音文件
        if ([recorder prepareToRecord] == YES) {
            [recorder record];

            recordSecond = 0;
            minuteRecord = 0;
            recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordSecondChange) userInfo:nil repeats:YES];
            [recordTimer fire];
        }
        
    }else {
        NSLog(@"錄音創(chuàng)建失敗");
    }
}


/**
 錄音計時
 */
- (void)recordSecondChange {
    
    recordSecond ++;
    if (recordSecond > 59) {
        
        minuteRecord ++;
        recordSecond = 0;
    }
    self.timeLbl.text = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)minuteRecord,(long)recordSecond];
}


/**
 停止錄音
 */
- (void)stopAction {
    
    NSLog(@"停止錄音");
    //停止錄音
    [recorder stop];
    recorder = nil;
    [recordTimer invalidate];
    recordTimer = nil;
    
    self.timeLbl.text = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)minuteRecord,(long)recordSecond];
}


/**
 播放錄音
 */
- (void)playAction {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSError *playError;
    
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:tmpUrl error:&playError];
    //當(dāng)播放錄音為空, 打印錯誤信息
    if (player == nil) {
        NSLog(@"Error crenting player: %@", [playError description]);
    }else {
        player.delegate = self;
        NSLog(@"開始播放");
        //開始播放
        playSecond = recordSecond;
        minutePlay = minuteRecord;
        if ([player prepareToPlay] == YES) {
           
            [player play];
            playTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playSecondChange) userInfo:nil repeats:YES];
            [playTimer fire];
        }
    }
}


/**
 播放計時
 */
- (void)playSecondChange {
    playSecond --;

    if (playSecond < 0) {
        
        if (minutePlay <= 0) {
            
            playSecond = 0;
            minutePlay = 0;
            [playTimer invalidate];
        }else{
            minutePlay --;
            playSecond = 59;
        }
        
    }
    self.timeLbl.text = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)minutePlay,(long)playSecond];
}


//當(dāng)播放結(jié)束后調(diào)用這個方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"播放結(jié)束");
    [playTimer invalidate];
    playTimer = nil;
    
    self.timeLbl.text = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)minuteRecord,(long)recordSecond];
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容