AudioUnit簡單的使用流程

#define kOutputBus 0

#define kInputBus 1

#define kSampleRate 8000

#define kFramesPerPacket 1

#define kChannelsPerFrame 1

#define kBitsPerChannel 16

#define SEND_PORT 9533

#define REC_PORT 9534

#define MAX_CLIENT_COUNT 20

#define BUFFER_SIZE 1024

@interface RemoteAudioProcessor : NSObject

@property (readonly) AudioComponentInstance audioUnit;

@property (readonly) AudioBuffer audioBuffer;

@property (strong, readwrite) NSMutableData *mIn;

@property (strong, readwrite) NSMutableData *mOut;

- (void)hasError:(int)statusCode file:(char*)file line:(int)line;

- (void)processBuffer: (AudioBufferList* )audioBufferList;

@end

//? RemoteAudioProcessor.m

//? AOIAudioSimulator

#import "RemoteAudioProcessor.h"

static NSMutableData *mIn;

static NSMutableData *mOut;

static bool mIsStarted; // audio unit start

static bool mSendServerStart; // send server continue loop

static bool mRecServerStart; // rec server continue loop

static bool mIsTele; // telephone call

static OSStatus recordingCallback(void *inRefCon,

AudioUnitRenderActionFlags *ioActionFlags,

const AudioTimeStamp *inTimeStamp,

UInt32 inBusNumber,

UInt32 inNumberFrames,

AudioBufferList *ioData) {

// the data gets rendered here

AudioBuffer buffer;

// a variable where we check the status

OSStatus status;

//This is the reference to the object who owns the callback.

RemoteAudioProcessor *audioProcessor = (__bridge RemoteAudioProcessor* )inRefCon;

/**

on this point we define the number of channels, which is mono

for the iphone. the number of frames is usally 512 or 1024.

*/

buffer.mDataByteSize = inNumberFrames * 2; // sample size

buffer.mNumberChannels = 1; // one channel

buffer.mData = malloc( inNumberFrames * 2 ); // buffer size

// we put our buffer into a bufferlist array for rendering

AudioBufferList bufferList;

bufferList.mNumberBuffers = 1;

bufferList.mBuffers[0] = buffer;

// render input and check for error

status = AudioUnitRender([audioProcessor audioUnit], ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, &bufferList);

[audioProcessor hasError:status file:__FILE__ line:__LINE__];

// process the bufferlist in the audio processor

[audioProcessor processBuffer: &bufferList];

// clean up the buffer

free(bufferList.mBuffers[0].mData);

return noErr;

}

#pragma mark Playback callback

static OSStatus playbackCallback(void *inRefCon,

AudioUnitRenderActionFlags *ioActionFlags,

const AudioTimeStamp *inTimeStamp,

UInt32 inBusNumber,

UInt32 inNumberFrames,

AudioBufferList *ioData) {

long len = [mIn length];

len = len > 1024 ? 1024 : len;

if (len <= 0) {

return noErr;

}

// to be changed

//? ? RemoteAudioProcessor *audioProcessor = (__bridge RemoteAudioProcessor* )inRefCon;

for (int i = 0; i < ioData -> mNumberBuffers; i++) {

ASLog( @"len:%ld", len);

AudioBuffer buffer = ioData -> mBuffers[i];

NSData *pcmBlock = [mIn subdataWithRange: NSMakeRange(0, len)];

UInt32 size = (UInt32)MIN(buffer.mDataByteSize, [pcmBlock length]);// ? buffer.mDataByteSize : [pcmBlock length];

memcpy(buffer.mData, [pcmBlock bytes], size);

[mIn replaceBytesInRange: NSMakeRange(0, size) withBytes: NULL length: 0];

buffer.mDataByteSize = size;

}

return noErr;

}

@implementation RemoteAudioProcessor

@synthesize audioUnit;

@synthesize audioBuffer;

/*

* It's Singleton pattern

* the flow is init(if there isn't existed self) -> initializeAudioConfig(set audio format, io pipe and callback functions)

*? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -> recordingCallback -> processBuffer

*? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -> playbackCallback

*/

- (RemoteAudioProcessor* )init {

self = [super init];

if (self) {

[self initializeAudioConfig];

mIn = [[NSMutableData alloc] init];

mOut = [[NSMutableData alloc] init];

mIsStarted = false;

mSendServerStart = false;

mRecServerStart = false;

mIsTele = false;

[NSThread detachNewThreadSelector:@selector(initSendSocketServer)

toTarget:self

withObject:nil];

[NSThread detachNewThreadSelector:@selector(initRecSocketServer)

toTarget:self

withObject:nil];

}

return self;

}

- (void)initializeAudioConfig {

OSStatus status;

AudioComponentDescription desc;

desc.componentType = kAudioUnitType_Output; // we want to ouput

desc.componentSubType = kAudioUnitSubType_RemoteIO; // we want in and ouput

desc.componentFlags = 0; // must be zero

desc.componentFlagsMask = 0; // must be zero

desc.componentManufacturer = kAudioUnitManufacturer_Apple; // select provider

AudioComponent inputComponent = AudioComponentFindNext(NULL, &desc);

status = AudioComponentInstanceNew(inputComponent, &audioUnit);

[self hasError:status file:__FILE__ line:__LINE__];

// define that we want record io on the input bus

UInt32 flag = 1;

status = AudioUnitSetProperty(audioUnit,

kAudioOutputUnitProperty_EnableIO, // use io

kAudioUnitScope_Input, // scope to input

kInputBus, // select input bus (1)

&flag, // set flag

sizeof(flag));

[self hasError:status file:__FILE__ line:__LINE__];

// define that we want play on io on the output bus

status = AudioUnitSetProperty(audioUnit,

kAudioOutputUnitProperty_EnableIO, // use io

kAudioUnitScope_Output, // scope to output

kOutputBus, // select output bus (0)

&flag, // set flag

sizeof(flag));

[self hasError:status file:__FILE__ line:__LINE__];

// specifie our format on which we want to work.

AudioStreamBasicDescription audioFormat;

audioFormat.mSampleRate = kSampleRate;

audioFormat.mFormatID = kAudioFormatLinearPCM;

audioFormat.mFormatFlags = kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger;

audioFormat.mFramesPerPacket = kFramesPerPacket;

audioFormat.mChannelsPerFrame = kChannelsPerFrame;

audioFormat.mBitsPerChannel = kBitsPerChannel;

audioFormat.mBytesPerPacket = kBitsPerChannel * kChannelsPerFrame * kFramesPerPacket / 8;

audioFormat.mBytesPerFrame = kBitsPerChannel * kChannelsPerFrame / 8;

// set the format on the output stream

status = AudioUnitSetProperty(audioUnit,

kAudioUnitProperty_StreamFormat,

kAudioUnitScope_Output,

kInputBus,

&audioFormat,

sizeof(audioFormat));

[self hasError:status file:__FILE__ line:__LINE__];

// set the format on the input stream

status = AudioUnitSetProperty(audioUnit,

kAudioUnitProperty_StreamFormat,

kAudioUnitScope_Input,

kOutputBus,

&audioFormat,

sizeof(audioFormat));

[self hasError:status file:__FILE__ line:__LINE__];

/**

We need to define a callback structure which holds

a pointer to the recordingCallback and a reference to

the audio processor object

*/

AURenderCallbackStruct callbackStruct;

// set recording callback struct

callbackStruct.inputProc = recordingCallback; // recordingCallback pointer

callbackStruct.inputProcRefCon = (__bridge void * _Nullable)(self);

// set input callback to recording callback on the input bus

status = AudioUnitSetProperty(audioUnit,

kAudioOutputUnitProperty_SetInputCallback,

kAudioUnitScope_Global,

kInputBus,

&callbackStruct,

sizeof(callbackStruct));

[self hasError:status file:__FILE__ line:__LINE__];

// set playback callback struct

callbackStruct.inputProc = playbackCallback;

callbackStruct.inputProcRefCon = (__bridge void * _Nullable)(self);

// set playbackCallback as callback on our renderer for the output bus

status = AudioUnitSetProperty(audioUnit,

kAudioUnitProperty_SetRenderCallback,

kAudioUnitScope_Global,

kOutputBus,

&callbackStruct,

sizeof(callbackStruct));

[self hasError:status file:__FILE__ line:__LINE__];

// reset flag to 0

flag = 0;

/*

we need to tell the audio unit to allocate the render buffer,

that we can directly write into it.

*/

status = AudioUnitSetProperty(audioUnit,

kAudioUnitProperty_ShouldAllocateBuffer,

kAudioUnitScope_Output,

kInputBus,

&flag,

sizeof(flag));

/*

we set the number of channels to mono and allocate our block size to

1024 bytes.

kiki: I don't know where the size 1024 bytes comes from...

*/

audioBuffer.mNumberChannels = kChannelsPerFrame;

audioBuffer.mDataByteSize = 512 * 2;

audioBuffer.mData = malloc( 512 * 2 );

// Initialize the Audio Unit and cross fingers =)

status = AudioUnitInitialize(audioUnit);

[self hasError:status file:__FILE__ line:__LINE__];

}

- (void)processBuffer: (AudioBufferList* )audioBufferList {

AudioBuffer sourceBuffer = audioBufferList -> mBuffers[0];

// we check here if the input data byte size has changed

if (audioBuffer.mDataByteSize != sourceBuffer.mDataByteSize) {

// clear old buffer

free(audioBuffer.mData);

// assing new byte size and allocate them on mData

audioBuffer.mDataByteSize = sourceBuffer.mDataByteSize;

audioBuffer.mData = malloc(sourceBuffer.mDataByteSize);

}

// copy incoming audio data to the audio buffer

memcpy(audioBuffer.mData, audioBufferList -> mBuffers[0].mData, audioBufferList -> mBuffers[0].mDataByteSize);

NSData *pcmBlock = [NSData dataWithBytes:sourceBuffer.mData length:sourceBuffer.mDataByteSize];

[mOut appendData: pcmBlock];

//

}

- (void)start {

if (mIsStarted) {

ASLog( @"-- already start --");

return;

}

ASLog( @"-- start --");

mIsStarted = true;

[mIn replaceBytesInRange: NSMakeRange(0, [mIn length]) withBytes: NULL length: 0];

[mOut replaceBytesInRange: NSMakeRange(0, [mOut length]) withBytes: NULL length: 0];

OSStatus status = AudioOutputUnitStart(audioUnit);

[self hasError:status file:__FILE__ line:__LINE__];

}

- (void)stop {

ASLog( @"-- stop --");

OSStatus status = AudioOutputUnitStop(audioUnit);

[self hasError:status file:__FILE__ line:__LINE__];

mIsStarted = false;

[mIn replaceBytesInRange: NSMakeRange(0, [mIn length]) withBytes: NULL length: 0];

[mOut replaceBytesInRange: NSMakeRange(0, [mOut length]) withBytes: NULL length: 0];

}

#pragma mark Error handling

- (void)hasError:(int)statusCode file:(char*)file line:(int)line {

if (statusCode) {

ASLog(@"Error Code responded %d in file %s on line %d", statusCode, file, line);

exit(-1);

}

}

#pragma mark Socket Implementation

- (int)initSendSocketServer {

struct sockaddr_in server_addr;

bzero(&server_addr, sizeof(server_addr));

server_addr.sin_family = AF_INET;

server_addr.sin_addr.s_addr = htons(INADDR_ANY);

server_addr.sin_port = htons(SEND_PORT);

int server_socket = socket(AF_INET, SOCK_STREAM, 0);

if (server_socket < 0) {

ASLog( @"Create send socket failed");

return -1;

}

int yes = 1;

setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {

[self closeSocket:server_socket error:@"Send Server bind failed"];

}

if (listen(server_socket, MAX_CLIENT_COUNT)) {

[self closeSocket:server_socket error:@"Send Server listen failed"];

}

mSendServerStart = true;

while (mSendServerStart) {

ASLog( @"wait send client");

struct sockaddr_in client_addr;

socklen_t length = sizeof(client_addr);

int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length);

if (client_socket < 0) {

ASLog( @"Create send client socket failed");

break;

}

[NSThread detachNewThreadSelector:@selector(sendClientRun:)

toTarget:self

withObject:[NSNumber numberWithInt:client_socket]];

}

close(server_socket);

return 0;

}

- (int)initRecSocketServer {

struct sockaddr_in server_addr;

bzero(&server_addr, sizeof(server_addr));

server_addr.sin_family = AF_INET;

server_addr.sin_addr.s_addr = htons(INADDR_ANY);

server_addr.sin_port = htons(REC_PORT);

int server_socket = socket(AF_INET, SOCK_STREAM, 0);

if (server_socket < 0) {

ASLog( @"Create rec socket failed");

return -1;

}

int yes = 1;

setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {

[self closeSocket:server_socket error:@"Rec Server bind failed"];

}

if (listen(server_socket, MAX_CLIENT_COUNT)) {

[self closeSocket:server_socket error:@"Rec Server listen failed"];

}

mSendServerStart = true;

while (mSendServerStart) {

ASLog( @"wait rec client");

struct sockaddr_in client_addr;

socklen_t length = sizeof(client_addr);

int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length);

if (client_socket < 0) {

ASLog( @"Create rec client socket failed");

break;

}

[NSThread detachNewThreadSelector:@selector(recClientRun:)

toTarget:self

withObject:[NSNumber numberWithInt:client_socket]];

}

close(server_socket);

return 0;

}

- (int)closeSocket: (int)socket

error: (NSString *)errorMsg {

if (errorMsg) {

ASLog(@"%@", errorMsg);

close(socket);

return -1;

} else {

close(socket);

return 0;

}

}

- (void)stopSocketServer {

mSendServerStart = false;

mRecServerStart = false;

}

- (void)sendClientRun: (NSNumber *)socket {

int client_socket = [socket intValue];

[self stop];

[self start];

ASLog( @"send client connection with %d", client_socket);

bool isClientAlive = true;

while (isClientAlive) {

if ([mOut length] <= 0) {

continue;

}

ssize_t res = send(client_socket, [mOut bytes], [mOut length], 0);

if (res > 0) {

[mOut replaceBytesInRange: NSMakeRange(0, res) withBytes: NULL length: 0];

} else {

isClientAlive = false;

[self closeSocket: client_socket error: @"send socket died"];

}

}

}

- (void)recClientRun: (NSNumber *)socket {

char buffer[BUFFER_SIZE];

int client_socket = [socket intValue];

ASLog( @"rec client connection with %d", client_socket);

bool isClientAlive = true;

while (isClientAlive) {

ssize_t res = recv(client_socket, buffer, BUFFER_SIZE, 0);

if (res > 0) {

NSData* pcmBlock = [[NSData alloc] initWithBytes: buffer length: res];

[mIn appendBytes: (__bridge const void * _Nonnull)(pcmBlock) length: res];

ASLog( @"rec:%zd", res);

} else {

isClientAlive = false;

[self closeSocket: client_socket error: @"rec socket died"];

}

}

}

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,048評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,414評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,169評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,722評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,465評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,823評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,813評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,000評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,554評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,295評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,513評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,722評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,125評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,430評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,237評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,482評論 2 379

推薦閱讀更多精彩內容