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. }  

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