iOS實現麥克風捕獲和AAC編碼

轉載地址:http://blog.csdn.net/shenyi0106/article/details/47004039


在Ios中,實現打開和捕獲麥克風大多是用的AVCaptureSession這個組件來實現的,它可以不僅可以實現音頻捕獲,還可以實現視頻的捕獲。本文將主要實現麥克風音頻的捕獲和編碼。

針對打開麥克風和捕獲音頻的代碼,網上也有一些,我就簡單的整理了一下:

首先,我們需要定義一個AVCaptureSession類型的變量,它是架起在麥克風設備和數據輸出上的一座橋,通過它可以方便的得到麥克風的實時原始數據。

[objc] view plaincopy
  1. AVCaptureSession *m_capture  

同時,定義一組函數,用來打開和關閉麥克風;爲了能使數據順利的導出,你還需要實現AVCaptureAudioDataOutputSampleBufferDelegate這個協議

[objc] view plaincopy
  1. -(void)open;  
  2. -(void)close;  
  3. -(BOOL)isOpen;  
下面我們將分別實現上述參數函數,來完成數據的捕獲。

[objc] view plaincopy
  1. -(void)open {  
  2.     NSError *error;  
  3.     m_capture = [[AVCaptureSession alloc]init];  
  4.     AVCaptureDevice *audioDev = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];  
  5.     if (audioDev == nil)  
  6.     {  
  7.         CKPrint("Couldn't create audio capture device");  
  8.         return ;  
  9.     }  
  10.       
  11.     // create mic device  
  12.     AVCaptureDeviceInput *audioIn = [AVCaptureDeviceInput deviceInputWithDevice:audioDev error:&error];  
  13.     if (error != nil)  
  14.     {  
  15.         CKPrint("Couldn't create audio input");  
  16.         return ;  
  17.     }  
  18.       
  19.       
  20.     // add mic device in capture object  
  21.     if ([m_capture canAddInput:audioIn] == NO)  
  22.     {  
  23.         CKPrint("Couldn't add audio input")  
  24.         return ;  
  25.     }  
  26.     [m_capture addInput:audioIn];  
  27.     // export audio data  
  28.     AVCaptureAudioDataOutput *audioOutput = [[AVCaptureAudioDataOutput alloc] init];  
  29.     [audioOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];  
  30.     if ([m_capture canAddOutput:audioOutput] == NO)  
  31.     {  
  32.         CKPrint("Couldn't add audio output");  
  33.         return ;  
  34.     }  
  35.     [m_capture addOutput:audioOutput];  
  36.     [audioOutput connectionWithMediaType:AVMediaTypeAudio];  
  37.     [m_capture startRunning];  
  38.     return ;  
  39. }  

[objc] view plaincopy
  1. -(void)close {  
  2.     if (m_capture != nil && [m_capture isRunning])  
  3.     {  
  4.         [m_capture stopRunning];  
  5.     }  
  6.       
  7.     return;  
  8. }  
  9. -(BOOL)isOpen {  
  10.     if (m_capture == nil)  
  11.     {  
  12.         return NO;  
  13.     }  
  14.       
  15.     return [m_capture isRunning];  
  16. }  
通過上面三個函數,即可完成所有麥克風捕獲的準備工作,現在我們就等着數據主動送上門了。要想數據主動送上門,我們還需要實現一個協議接口:

[objc] view plaincopy
  1. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {  
  2.     char szBuf[4096];  
  3.     int  nSize = sizeof(szBuf);  
  4.       
  5. #if SUPPORT_AAC_ENCODER  
  6.     if ([self encoderAAC:sampleBuffer aacData:szBuf aacLen:&nSize] == YES)  
  7.     {  
  8.         [g_pViewController sendAudioData:szBuf len:nSize channel:0];  
  9.     }  
  10. #else //#if SUPPORT_AAC_ENCODER  
  11.     AudioStreamBasicDescription outputFormat = *(CMAudioFormatDescriptionGetStreamBasicDescription(CMSampleBufferGetFormatDescription(sampleBuffer)));  
  12.     nSize = CMSampleBufferGetTotalSampleSize(sampleBuffer);  
  13.     CMBlockBufferRef databuf = CMSampleBufferGetDataBuffer(sampleBuffer);  
  14.     if (CMBlockBufferCopyDataBytes(databuf, 0, nSize, szBuf) == kCMBlockBufferNoErr)  
  15.     {  
  16.         [g_pViewController sendAudioData:szBuf len:nSize channel:outputFormat.mChannelsPerFrame];  
  17.     }  
  18. #endif  
  19. }  
到這裏,我們的工作也就差不多做完了,所捕獲出來的數據是原始的PCM數據。

當然,由於PCM數據本身比較大,不利於網絡傳輸,所以如果需要進行網絡傳輸時,就需要對數據進行編碼;Ios系統本身支持多種音頻編碼格式,這裏我們就以AAC爲例來實現一個PCM編碼AAC的函數。


在Ios系統中,PCM編碼AAC的例子,在網上也是一找一大片,但是大多都是不太完整的,而且相當一部分都是E文的,對於某些童鞋而言,這些都是深惡痛絕的。我這裏就做做好人,把它們整理了一下,寫成了一個函數,方便使用。

在編碼前,需要先創建一個編碼轉換對象

[objc] view plaincopy
  1. AVAudioConverterRef m_converter;  

[objc] view plaincopy
  1. #if SUPPORT_AAC_ENCODER  
  2. -(BOOL)createAudioConvert:(CMSampleBufferRef)sampleBuffer { //根據輸入樣本初始化一個編碼轉換器  
  3.     if (m_converter != nil)  
  4.     {  
  5.         return TRUE;  
  6.     }  
  7.       
  8.     AudioStreamBasicDescription inputFormat = *(CMAudioFormatDescriptionGetStreamBasicDescription(CMSampleBufferGetFormatDescription(sampleBuffer))); // 輸入音頻格式  
  9.     AudioStreamBasicDescription outputFormat; // 這裏開始是輸出音頻格式  
  10.     memset(&outputFormat, 0sizeof(outputFormat));  
  11.     outputFormat.mSampleRate       = inputFormat.mSampleRate// 採樣率保持一致  
  12.     outputFormat.mFormatID         = kAudioFormatMPEG4AAC;    // AAC編碼  
  13.     outputFormat.mChannelsPerFrame = 2;  
  14.     outputFormat.mFramesPerPacket  = 1024;                    // AAC一幀是1024個字節  
  15.       
  16.     AudioClassDescription *desc = [self getAudioClassDescriptionWithType:kAudioFormatMPEG4AAC fromManufacturer:kAppleSoftwareAudioCodecManufacturer];  
  17.     if (AudioConverterNewSpecific(&inputFormat, &outputFormat, 1, desc, &m_converter) != noErr)  
  18.     {  
  19.         CKPrint(@"AudioConverterNewSpecific failed");  
  20.         return NO;  
  21.     }  
  22.   
  23.     return YES;  
  24. }  
  25. -(BOOL)encoderAAC:(CMSampleBufferRef)sampleBuffer aacData:(char*)aacData aacLen:(int*)aacLen { // 編碼PCM成AAC  
  26.     if ([self createAudioConvert:sampleBuffer] != YES)  
  27.     {  
  28.         return NO;  
  29.     }  
  30.       
  31.     CMBlockBufferRef blockBuffer = nil;  
  32.     AudioBufferList  inBufferList;  
  33.     if (CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, NULL, &inBufferList, sizeof(inBufferList), NULLNULL0, &blockBuffer) != noErr)  
  34.     {  
  35.         CKPrint(@"CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer failed");  
  36.         return NO;  
  37.     }  
  38.     // 初始化一個輸出緩衝列表  
  39.     AudioBufferList outBufferList;  
  40.     outBufferList.mNumberBuffers              = 1;  
  41.     outBufferList.mBuffers[0].mNumberChannels = 2;  
  42.     outBufferList.mBuffers[0].mDataByteSize   = *aacLen; // 設置緩衝區大小  
  43.     outBufferList.mBuffers[0].mData           = aacData; // 設置AAC緩衝區  
  44.     UInt32 outputDataPacketSize               = 1;  
  45.     if (AudioConverterFillComplexBuffer(m_converter, inputDataProc, &inBufferList, &outputDataPacketSize, &outBufferList, NULL) != noErr)  
  46.     {  
  47.         CKPrint(@"AudioConverterFillComplexBuffer failed");  
  48.         return NO;  
  49.     }  
  50.       
  51.     *aacLen = outBufferList.mBuffers[0].mDataByteSize//設置編碼後的AAC大小  
  52.     CFRelease(blockBuffer);  
  53.     return YES;  
  54. }  
  55. -(AudioClassDescription*)getAudioClassDescriptionWithType:(UInt32)type fromManufacturer:(UInt32)manufacturer { // 獲得相應的編碼器  
  56.     static AudioClassDescription audioDesc;  
  57.       
  58.     UInt32 encoderSpecifier = type, size = 0;  
  59.     OSStatus status;  
  60.       
  61.     memset(&audioDesc, 0sizeof(audioDesc));  
  62.     status = AudioFormatGetPropertyInfo(kAudioFormatProperty_Encoders, sizeof(encoderSpecifier), &encoderSpecifier, &size);  
  63.     if (status)  
  64.     {  
  65.         return nil;  
  66.     }  
  67.       
  68.     uint32_t count = size / sizeof(AudioClassDescription);  
  69.     AudioClassDescription descs[count];  
  70.     status = AudioFormatGetProperty(kAudioFormatProperty_Encoders, sizeof(encoderSpecifier), &encoderSpecifier, &size, descs);  
  71.     for (uint32_t i = 0; i < count; i++)  
  72.     {  
  73.         if ((type == descs[i].mSubType) && (manufacturer == descs[i].mManufacturer))  
  74.         {  
  75.             memcpy(&audioDesc, &descs[i], sizeof(audioDesc));  
  76.             break;  
  77.         }  
  78.     }  
  79.     return &audioDesc;  
  80. }  
  81. OSStatus inputDataProc(AudioConverterRef inConverter, UInt32 *ioNumberDataPackets, AudioBufferList *ioData,AudioStreamPacketDescription **outDataPacketDescription, voidvoid *inUserData) { //<span style="font-family: Arial, Helvetica, sans-serif;">AudioConverterFillComplexBuffer 編碼過程中,會要求這個函數來填充輸入數據,也就是原始PCM數據</span>  
  82.     AudioBufferList bufferList = *(AudioBufferList*)inUserData;  
  83.     ioData->mBuffers[0].mNumberChannels = 1;  
  84.     ioData->mBuffers[0].mData           = bufferList.mBuffers[0].mData;  
  85.     ioData->mBuffers[0].mDataByteSize   = bufferList.mBuffers[0].mDataByteSize;  
  86.     return noErr;  
  87. }  
  88. #endif  
好了,世界是那麼美好,一個函數即可所有的事情搞定了。當你需要進行AAC編碼時,調用encoderAAC這個函數就可以了(在上面有完整的代碼)

[objc] view plaincopy
  1. char szBuf[4096];  
  2. int  nSize = sizeof(szBuf);  
  3. if ([self encoderAAC:sampleBuffer aacData:szBuf aacLen:&nSize] == YES)  
  4. {  
  5.     // do something   
  6. }  

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