LoginSignup
1
1

More than 5 years have passed since last update.

AudioUnit Sample On cocos2d

Last updated at Posted at 2012-05-25
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import <AudioUnit/AudioUnit.h>

@interface SoundBox : CCLayer {

    AudioUnit audioUnit;

    float phase;
    float samplingRate;
    float sineWaveFrequency;
    float fraquency;

}

+(id)soundBox;
-(id)initSoundBox;

-(void)start;
-(void)stop;

@property (nonatomic) float phase;
@property (nonatomic) float samplingRate;
@property (nonatomic) float sineWaveFrequency;
@property (nonatomic) float frequency;


@end
#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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1