// // AudioCapture.m // live // // Created by lujunjie on 2016/11/5. // Copyright © 2016年 lujunjie. All rights reserved. // #import "AudioQueueCapture.h" #import <AudioToolbox/AudioToolbox.h> #define QUEUE_BUFFER_SIZE 10 //隊列緩衝個數 #define MIN_SIZE_PER_FRAME 1000 //每幀最小數據長度 @interface AudioQueueCapture() { AudioQueueRef audioQueue;//音頻播放隊列 AudioQueueBufferRef audioQueueBuffer[QUEUE_BUFFER_SIZE];//音頻緩存 AudioStreamBasicDescription audioDescription;//音頻參數 } @end @implementation AudioQueueCapture - (instancetype)init { if (self=[super init]) { audioDescription.mSampleRate = 8000;//採樣率 audioDescription.mFormatID = kAudioFormatLinearPCM; audioDescription.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; audioDescription.mChannelsPerFrame = 1;///單聲道 每一幀數據包含的通道數 audioDescription.mFramesPerPacket = 1;//每一個包數據的樣本幀的數量 audioDescription.mBitsPerChannel = 16;//每一個採樣點16bit量化 每一幀數據的每個通道的採樣位的數量 audioDescription.mBytesPerPacket = 2; // 每一個包數據的字節數量 audioDescription.mBytesPerFrame = 2;//單幀包含的字節數據 } return self; } - (void)stop { if (audioQueue) { AudioQueueStop(audioQueue, YES); AudioQueueDispose(audioQueue, YES); audioQueue = NULL; } } - (void)start { // 建立音頻輸入隊列 if (AudioQueueNewInput(&audioDescription, audioQueueInputCallback, (__bridge void * _Nullable)(self), NULL, NULL, 0, &audioQueue) != noErr){ return; } for (int i = 0; i < QUEUE_BUFFER_SIZE; i++) { //請求音頻隊列對象來分配一個音頻隊列緩存。 AudioQueueAllocateBuffer(audioQueue, MIN_SIZE_PER_FRAME, &audioQueueBuffer[i]); //給錄音或者回放音頻隊列的緩存中添加一個緩存數據 AudioQueueEnqueueBuffer(audioQueue, audioQueueBuffer[i], 0, NULL); } if (audioQueue) { //開始錄音 AudioQueueStart(audioQueue, NULL); } } void audioQueueInputCallback (void *inUserData,AudioQueueRef inoQueueRef, AudioQueueBufferRef inBuffer,const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription *inPacketDescs) { AudioQueueCapture *self = (__bridge AudioQueueCapture *)inUserData; [self.delegate audioQueueCaptureData:inBuffer->mAudioData dataLength:inBuffer->mAudioDataBytesCapacity]; AudioQueueEnqueueBuffer(inoQueueRef, inBuffer, 0, NULL); } - (void)dealloc { [self stop]; self.delegate = nil; } @end