AudioUnit簡(jiǎn)單的使用流程

#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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市最疆,隨后出現(xiàn)的幾起案子箫章,更是在濱河造成了極大的恐慌,老刑警劉巖镣屹,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異生巡,居然都是意外死亡牲尺,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)幌蚊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)谤碳,“玉大人,你說(shuō)我怎么就攤上這事溢豆⊙鸭颍” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵漩仙,是天一觀的道長(zhǎng)搓茬。 經(jīng)常有香客問(wèn)我,道長(zhǎng)队他,這世上最難降的妖魔是什么卷仑? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮麸折,結(jié)果婚禮上系枪,老公的妹妹穿的比我還像新娘。我一直安慰自己磕谅,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布雾棺。 她就那樣靜靜地躺著膊夹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪捌浩。 梳的紋絲不亂的頭發(fā)上放刨,一...
    開(kāi)封第一講書(shū)人閱讀 51,554評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音尸饺,去河邊找鬼进统。 笑死助币,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的螟碎。 我是一名探鬼主播眉菱,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼掉分!你這毒婦竟也來(lái)了俭缓?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤酥郭,失蹤者是張志新(化名)和其女友劉穎华坦,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體不从,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡惜姐,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了椿息。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片歹袁。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖撵颊,靈堂內(nèi)的尸體忽然破棺而出宇攻,到底是詐尸還是另有隱情,我是刑警寧澤倡勇,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布逞刷,位于F島的核電站,受9級(jí)特大地震影響妻熊,放射性物質(zhì)發(fā)生泄漏夸浅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一扔役、第九天 我趴在偏房一處隱蔽的房頂上張望帆喇。 院中可真熱鬧,春花似錦亿胸、人聲如沸坯钦。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)婉刀。三九已至,卻和暖如春序仙,著一層夾襖步出監(jiān)牢的瞬間突颊,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留律秃,地道東北人爬橡。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像棒动,于是被迫代替她去往敵國(guó)和親糙申。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容