錄製音頻(AVAudioRecorder)for iOS

由於本人沒有進行過專門的錄製音頻的項目開發,所以這裏只是能完成一個可以錄音的小demo。so,首先說一下蘋果的API,AVFounditon.framework下的AVAudioRecorder。

AVAudioRecorder和AVAudioPlayer類似,功能類似於一個錄音器,使用AVAudioRecorder錄製視頻十分簡單。一般需要三步:

1、創建AVAudioRecorder對象,需要注意的是在創建AVAudioRecorder之前,需要準備一個NSDictiion的對象,對象中封裝音頻設置相關的音頻信息。具體的key有AVFormatIDKey(音頻格式)、AVSampleRateKey(採樣率)、AVNumberOfChannelsKey(聲道數)等,具體參照蘋果的文檔。關於聲音有關的知識,只能求助於度娘了。

2、監聽錄製完成和被中斷的事件。設置AVAudioRecorder代理,這裏需要說明的是ios9已經廢棄了AVAudioRecorder的中斷代理方法,改用AVAudioSession的代理方法。

3、調用record方法錄音。播放錄音結果,用AVAudioPlayer。


具體實現

1、導入AVFounditon頭文件,#import<Foundation/Foundation.h>

2、設置音頻會話,並設置音頻類別和激活當前音頻會話

- (void)viewDidLoad {

    [superviewDidLoad];

    [self.recorderBtnsetBackgroundImage:recordImageforState:UIControlStateNormal];

    //獲取當前應用的音頻會話

    AVAudioSession * audioSession = [AVAudioSessionsharedInstance];

    //設置音頻類別,PlayAndRecord——這說明當前音頻會話即可播放、也可錄製

    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecorderror: nil];

    //激活當前應用的音頻會話

    [audioSessionsetActive:YESerror: nil];

}

3、創建AVAudioRecorder和AVAudioPlayer,這裏需要注意:這兩個對象要設置爲全局變量,要不然錄音不成功

<1>設置NSDictionary

// 創建一個NSDictionary,用於保存錄制屬性

NSMutableDictionary *recordSettings = [[NSMutableDictionaryalloc] init];

// 設置錄製音頻的格式

[recordSettings setObject:[NSNumbernumberWithInt:kAudioFormatLinearPCM]

                          forKey: AVFormatIDKey];

NSString* sampleRate = [self.sampleRateSegtitleForSegmentAtIndex:

                               self.sampleRateSeg.selectedSegmentIndex];

// 設置錄製音頻的採樣率

[recordSettingssetObject:[NSNumbernumberWithFloat:

                                   sampleRate.floatValue]forKey: AVSampleRateKey];

// 設置錄製音頻的通道數

[recordSettingssetObject:

         [NSNumbernumberWithInt:(self.stereoSwitch.on ?2 : 1)] forKey:AVNumberOfChannelsKey];

NSString* bitDepth = [self.bitDeptSegtitleForSegmentAtIndexself.bitDeptSeg.selectedSegmentIndex];

// 設置錄製音頻的每個樣點的位數

[recordSettingssetObject: [NSNumbernumberWithInt:bitDepth.intValueforKey:AVLinearPCMBitDepthKey];

// 設置錄製音頻採用高位優先的記錄格式

[recordSettingssetObject:[NSNumbernumberWithBool:YESforKey:AVLinearPCMIsBigEndianKey];

// 設置採樣信號採用浮點數

[recordSettingssetObject:[NSNumbernumberWithBool:YESforKey:AVLinearPCMIsFloatKey];


<2>創建對象並設置代理,實現代理方法

// 初始化AVAudioRecorder

audioRecorder = [[AVAudioRecorderalloc] initWithURL:destinationURL settings:recordSettings error:&recorderSetupError];

audioRecorder.delegate = self;


<3>錄製音頻,在音頻沒有準備好的時候也會默認調用prepareToRecord方法

[audioRecorder record];






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章