#import "SoundBox.h"
@implementation SoundBox
@synthesize phase;
@synthesize samplingRate;
@synthesize sineWaveFrequency;
@synthesize frequency;
+(id)soundBox
{
return [[self alloc]initSoundBox];
}
-(id)initSoundBox
{
if((self = [super init]))
{
self.samplingRate = 44100;
self.sineWaveFrequency = 440;
self.frequency = self.sineWaveFrequency * 2 * M_PI / self.samplingRate;
[self prepareAudioUnit];
}
return self;
}
-(void)start
{
AudioOutputUnitStart(audioUnit);
}
-(void)stop
{
AudioOutputUnitStop(audioUnit);
}
OSStatus AURenderCallBack(void *inRefcon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData)
{
SoundBox *soundBox = (__bridge SoundBox *)inRefcon;
soundBox.frequency = soundBox.sineWaveFrequency * 2 * M_PI / soundBox.samplingRate;
//float *outL = ioData->mBuffers[1].mData;
float *outR = ioData->mBuffers[0].mData;
for(int i = 0;i < (int)inNumberFrames;i++)
{
float wave = sin(soundBox.phase);
//*outL++ = wave;
*outR++ = wave;
soundBox.phase += soundBox.frequency;
}
return noErr;
}
-(void)prepareAudioUnit
{
AudioComponentDescription cd;
cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_RemoteIO;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;
cd.componentFlagsMask = 0;
cd.componentFlags = 0;
AudioComponent component = AudioComponentFindNext(NULL, &cd);
AudioComponentInstanceNew(component, &audioUnit);
AudioUnitInitialize(audioUnit);
AURenderCallbackStruct callBackStruct;
callBackStruct.inputProc = AURenderCallBack;
callBackStruct.inputProcRefCon = (__bridge void*)self;
AudioUnitSetProperty(audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callBackStruct, sizeof(callBackStruct));
//AudioOutputUnitStart(audioUnit);
}
@end