Thursday, April 21, 2011

Audio Recording in Mac App


I had spent much time researching on this .Finally , I am happy to share this with all of you.


Steps for integrating this includes :

1. Add the following frameworks to your app as existing frameworks

a) QTKit.framework
b) AudioUnit.framework
c) AudioToolbox.framework

2. in your .h file add the below code

#import <Cocoa/Cocoa.h>
#import <AudioUnit/AudioUnit.h>
#import <AudioToolbox/AudioToolbox.h>
@class QTCaptureSession;
@class QTCaptureDeviceInput;
@class QTCaptureDecompressedAudioOutput;
@interface CaptureSessionController : NSObject <NSWindowDelegate> {
IBOutlet NSWindow *window;
@private
QTCaptureSession *captureSession;
QTCaptureDeviceInput *captureAudioDeviceInput;
QTCaptureDecompressedAudioOutput *captureAudioDataOutput;
AudioUnit effectAudioUnit;
ExtAudioFileRef extAudioFile;
AudioStreamBasicDescription currentInputASBD;
AudioBufferList *currentInputAudioBufferList;
double currentSampleTime;
BOOL didSetUpAudioUnits;
NSString *outputFile;
BOOL recording;
}
@property(copy) NSString *outputFile;
@property(getter=isRecording) BOOL recording;
- (IBAction)chooseOutputFile:(id)sender;
@end


3. In your .m file add the below code

#import "CaptureSessionController.h"
#import <QTKit/QTKit.h>
static OSStatus PushCurrentInputBufferIntoAudioUnit(void * inRefCon,
AudioUnitRenderActionFlags * ioActionFlags,
const AudioTimeStamp * inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList * ioData);
@implementation CaptureSessionController
#pragma mark ======== Setup and teardown methods =========
- (id)init
{
self = [super init];
if (self) {
[self setOutputFile:[@"~/Desktop/Audio Recording.aif" stringByStandardizingPath]];
}
return self;
}
- (void)awakeFromNib
{
BOOL success;
NSError *error;
/* Find and open an audio input device. */
QTCaptureDevice *audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeSound];
success = [audioDevice open:&error];
if (!success) {
[[NSAlert alertWithError:error] runModal];
return;
}
/* Create the capture session. */
captureSession = [[QTCaptureSession alloc] init];
/* Add a device input for the audio device to the session. */
captureAudioDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice:audioDevice];
success = [captureSession addInput:captureAudioDeviceInput error:&error];
if (!success) {
[captureAudioDeviceInput release];
captureAudioDeviceInput = nil;
[audioDevice close];
[captureSession release];
captureSession = nil;
[[NSAlert alertWithError:error] runModal];
return;
}
/* Create an audio data output for reading captured audio buffers and add it to the capture session. */
captureAudioDataOutput = [[QTCaptureDecompressedAudioOutput alloc] init];
[captureAudioDataOutput setDelegate:self]; /* Captured audio buffers will be provided to the delegate via the captureOutput:didOutputAudioSampleBuffer:fromConnection: delegate method. */
success = [captureSession addOutput:captureAudioDataOutput error:&error];
if (!success) {
[captureAudioDeviceInput release];
captureAudioDeviceInput = nil;
[audioDevice close]; 
[captureAudioDataOutput release];
captureAudioDataOutput = nil;
[captureSession release];
captureSession = nil;
[[NSAlert alertWithError:error] runModal];
return;
}
/* Create an effect audio unit to add an effect to the audio before it is written to a file. */
OSStatus err = noErr;
AudioComponentDescription effectAudioUnitComponentDescription;
effectAudioUnitComponentDescription.componentType = kAudioUnitType_Effect;
effectAudioUnitComponentDescription.componentSubType = kAudioUnitSubType_Delay;
effectAudioUnitComponentDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
effectAudioUnitComponentDescription.componentFlags = 0;
effectAudioUnitComponentDescription.componentFlagsMask = 0;
AudioComponent effectAudioUnitComponent = AudioComponentFindNext(NULL, &effectAudioUnitComponentDescription);
err = AudioComponentInstanceNew(effectAudioUnitComponent, &effectAudioUnit);
if (noErr == err) {
/* Set a callback on the effect unit that will supply the audio buffers received from the audio data output. */
AURenderCallbackStruct renderCallbackStruct;
renderCallbackStruct.inputProc = PushCurrentInputBufferIntoAudioUnit;
renderCallbackStruct.inputProcRefCon = self;
err = AudioUnitSetProperty(effectAudioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallbackStruct, sizeof(renderCallbackStruct)); 
}
if (noErr != err) {
if (effectAudioUnit) {
AudioComponentInstanceDispose(effectAudioUnit);
effectAudioUnit = NULL;
}
[captureAudioDeviceInput release];
captureAudioDeviceInput = nil;
[audioDevice close];
[captureSession release];
captureSession = nil;
[[NSAlert alertWithError:[NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]] runModal];
return;
}
/* Start the capture session. This will cause the audo data output delegate method to be called for each new audio buffer that is captured from the input device. */
[captureSession startRunning];
/* Become the window's delegate so that the capture session can be stopped and cleaned up immediately after the window is closed. */
[window setDelegate:self];
}
- (void)windowWillClose:(NSNotification *)notification
{
[self setRecording:NO];
[captureSession stopRunning];
QTCaptureDevice *audioDevice = [captureAudioDeviceInput device];
if ([audioDevice isOpen])
[audioDevice close];
}
- (void)dealloc
{
[captureSession release];
[captureAudioDeviceInput release];
[captureAudioDataOutput release];
[outputFile release];
if (extAudioFile)
ExtAudioFileDispose(extAudioFile);
if (effectAudioUnit) {
if (didSetUpAudioUnits)
AudioUnitUninitialize(effectAudioUnit);
AudioComponentInstanceDispose(effectAudioUnit);
}
[super dealloc];
}
#pragma mark ======== Audio capture methods =========
/*
Called periodically by the QTCaptureAudioDataOutput as it receives QTSampleBuffer objects containing audio frames captured by the QTCaptureSession.
Each QTSampleBuffer will contain multiple frames of audio encoded in the canonical non-interleaved linear PCM format compatible with AudioUnits.
*/
- (void)captureOutput:(QTCaptureOutput *)captureOutput didOutputAudioSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection
{
OSStatus err = noErr;
BOOL isRecording = [self isRecording];
/* Get the sample buffer's AudioStreamBasicDescription, which will be used to set the input format of the effect audio unit and the ExtAudioFile. */
QTFormatDescription *formatDescription = [sampleBuffer formatDescription];
NSValue *sampleBufferASBDValue = [formatDescription attributeForKey:QTFormatDescriptionAudioStreamBasicDescriptionAttribute];
if (!sampleBufferASBDValue)
return;
AudioStreamBasicDescription sampleBufferASBD = {0};
[sampleBufferASBDValue getValue:&sampleBufferASBD]; 
if ((sampleBufferASBD.mChannelsPerFrame != currentInputASBD.mChannelsPerFrame) || (sampleBufferASBD.mSampleRate != currentInputASBD.mSampleRate)) {
/* Although QTCaptureAudioDataOutput guarantees that it will output sample buffers in the canonical format, the number of channels or the
sample rate of the audio can changes at any time while the capture session is running. If this occurs, the audio unit receiving the buffers
from the QTCaptureAudioDataOutput needs to be reconfigured with the new format. This also must be done when a buffer is received for the
first time. */
currentInputASBD = sampleBufferASBD;
if (didSetUpAudioUnits) {
/* The audio units were previously set up, so they must be uninitialized now. */
AudioUnitUninitialize(effectAudioUnit);
/* If recording was in progress, the recording needs to be stopped because the audio format changed. */
if (extAudioFile) {
ExtAudioFileDispose(extAudioFile);
extAudioFile = NULL;
}
} else {
didSetUpAudioUnits = YES;
}
/* Set the input and output formats of the effect audio unit to match that of the sample buffer. */
err = AudioUnitSetProperty(effectAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &currentInputASBD, sizeof(currentInputASBD));
if (noErr == err)
err = AudioUnitSetProperty(effectAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &currentInputASBD, sizeof(currentInputASBD));
if (noErr == err)
err = AudioUnitInitialize(effectAudioUnit);
if (noErr != err) {
NSLog(@"Failed to set up audio units (%d)", err);
didSetUpAudioUnits = NO;
bzero(&currentInputASBD, sizeof(currentInputASBD));
}
}
if (isRecording && !extAudioFile) {
/* Start recording by creating an ExtAudioFile and configuring it with the same sample rate and channel layout as those of the current sample buffer. */
AudioStreamBasicDescription recordedASBD = {0};
recordedASBD.mSampleRate = currentInputASBD.mSampleRate;
recordedASBD.mFormatID = kAudioFormatLinearPCM;
recordedASBD.mFormatFlags = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
recordedASBD.mBytesPerPacket = 2 * currentInputASBD.mChannelsPerFrame;
recordedASBD.mFramesPerPacket = 1;
recordedASBD.mBytesPerFrame = 2 * currentInputASBD.mChannelsPerFrame;
recordedASBD.mChannelsPerFrame = currentInputASBD.mChannelsPerFrame;
recordedASBD.mBitsPerChannel = 16;
NSData *inputChannelLayoutData = [formatDescription attributeForKey:QTFormatDescriptionAudioChannelLayoutAttribute];
AudioChannelLayout *recordedChannelLayout = (AudioChannelLayout *)[inputChannelLayoutData bytes];
err = ExtAudioFileCreateWithURL((CFURLRef)[NSURL fileURLWithPath:[self outputFile]],
kAudioFileAIFFType,
&recordedASBD,
recordedChannelLayout,
kAudioFileFlags_EraseFile,
&extAudioFile);
if (noErr == err) 
err = ExtAudioFileSetProperty(extAudioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(currentInputASBD), &currentInputASBD);
if (noErr != err) {
NSLog(@"Failed to set up ExtAudioFile (%d)", err);
ExtAudioFileDispose(extAudioFile);
extAudioFile = NULL;
}
} else if (!isRecording && extAudioFile) {
/* Stop recording by disposing of the ExtAudioFile. */
ExtAudioFileDispose(extAudioFile);
extAudioFile = NULL;
}
NSUInteger numberOfFrames = [sampleBuffer numberOfSamples]; /* -[QTSampleBuffer numberOfSamples] corresponds to the number of CoreAudio audio frames. */
/* In order to render continuously, the effect audio unit needs a new time stamp for each buffer. Use the number of frames for each unit of time. */
currentSampleTime += (double)numberOfFrames;
AudioTimeStamp timeStamp = {0};
timeStamp.mSampleTime = currentSampleTime;
timeStamp.mFlags |= kAudioTimeStampSampleTimeValid; 
AudioUnitRenderActionFlags flags = 0;
/* Create an AudioBufferList large enough to hold the number of frames from the sample buffer in 32-bit floating point PCM format. */
AudioBufferList *outputABL = calloc(1, sizeof(*outputABL) + (currentInputASBD.mChannelsPerFrame - 1)*sizeof(outputABL->mBuffers[0]));
outputABL->mNumberBuffers = currentInputASBD.mChannelsPerFrame;
UInt32 channelIndex;
for (channelIndex = 0; channelIndex < currentInputASBD.mChannelsPerFrame; channelIndex++) {
UInt32 dataSize = numberOfFrames * currentInputASBD.mBytesPerFrame;
outputABL->mBuffers[channelIndex].mDataByteSize = dataSize;
outputABL->mBuffers[channelIndex].mData = malloc(dataSize);
outputABL->mBuffers[channelIndex].mNumberChannels = 1;
}
/*
Get an audio buffer list from the sample buffer and assign it to the currentInputAudioBufferList instance variable.
The the effect audio unit render callback, PushCurrentInputBufferIntoAudioUnit(), can access this value by calling the currentInputAudioBufferList method.
*/
currentInputAudioBufferList = [sampleBuffer audioBufferListWithOptions:QTSampleBufferAudioBufferListOptionAssure16ByteAlignment];
/* Tell the effect audio unit to render. This will synchronously call PushCurrentInputBufferIntoAudioUnit(), which will feed the audio buffer list into the effect audio unit. */
err = AudioUnitRender(effectAudioUnit, &flags, &timeStamp, 0, numberOfFrames, outputABL);
currentInputAudioBufferList = NULL;
if ((noErr == err) && extAudioFile) {
err = ExtAudioFileWriteAsync(extAudioFile, numberOfFrames, outputABL);
}
for (channelIndex = 0; channelIndex < currentInputASBD.mChannelsPerFrame; channelIndex++) {
free(outputABL->mBuffers[channelIndex].mData);
}
free(outputABL);
}
/* Used by PushCurrentInputBufferIntoAudioUnit() to access the current audio buffer list that has been output by the QTCaptureAudioDataOutput. */
- (AudioBufferList *)currentInputAudioBufferList
{
return currentInputAudioBufferList;
}
#pragma mark ======== Property and action definitions =========
@synthesize outputFile = outputFile;
@synthesize recording = recording;
- (IBAction)chooseOutputFile:(id)sender
{
NSSavePanel *savePanel = [NSSavePanel savePanel];
[savePanel setAllowedFileTypes:[NSArray arrayWithObject:@"aif"]];
[savePanel setCanSelectHiddenExtension:YES];
NSInteger result = [savePanel runModal];
if (NSOKButton == result) {
[self setOutputFile:[savePanel filename]];
}
}
@end
#pragma mark ======== AudioUnit render callback =========
/*
Synchronously called by the effect audio unit whenever AudioUnitRender() us called.
Used to feed the audio samples output by the ATCaptureAudioDataOutput to the AudioUnit.
*/
static OSStatus PushCurrentInputBufferIntoAudioUnit(void * inRefCon,
AudioUnitRenderActionFlags * ioActionFlags,
const AudioTimeStamp * inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList * ioData)
{
CaptureSessionController *self = (CaptureSessionController *)inRefCon;
AudioBufferList *currentInputAudioBufferList = [self currentInputAudioBufferList];
UInt32 bufferIndex, bufferCount = currentInputAudioBufferList->mNumberBuffers;
if (bufferCount != ioData->mNumberBuffers)
return badFormat;
/* Fill the provided AudioBufferList with the data from the AudioBufferList output by the audio data output. */
for (bufferIndex = 0; bufferIndex < bufferCount; bufferIndex++) {
ioData->mBuffers[bufferIndex].mDataByteSize = currentInputAudioBufferList->mBuffers[bufferIndex].mDataByteSize;
ioData->mBuffers[bufferIndex].mData = currentInputAudioBufferList->mBuffers[bufferIndex].mData;
ioData->mBuffers[bufferIndex].mNumberChannels = currentInputAudioBufferList->mBuffers[bufferIndex].mNumberChannels;
}
return noErr;
}

4. In your xib add a button for recording to start & stop.I have a NSButton in the contentView of my window. Your xib should like


Click for full-size image

5.You also need to set the bindings for the NSButton .For that select the button Bindings in your Attributes Inspector.


Thursday, April 7, 2011

Dropbox Integration in Iphone


Requirements:


1. You need the 4.0 version of the iPhone SDK. The version of your XCode should
be at least 3.2.3.
2. You need to have registered as a Dropbox application with mobile access at
http://dropbox.com/developers. You should have a consumer key and secret.
3. You need to download the dropbox sdk from https://www.dropbox.com/developers/releases

A. Adding DropboxSDK to your project


1. Open your project in XCode
2. Right-click on your project in the group tree in the left pane
3. Select Add -> Existing Files...
4. Navigate to where you uncompressed the Dropbox SDK and select the DropboxSDK
subfolder
5. Select "Copy items into destination group's folder"
6. Make sure "Recursively create groups for any added folders" is selected
7. Press Add button
8. Find the Frameworks folder in your app's group tree in the left pane
9. Make sure the framework Security.framework is added to your project
10. If not, right-click on Frameworks and select Add -> Existing Frameworks...
11. Select Security.framework from the list and select Add
12. Build your application. At this point you should have no build failures or
warning

B. Login successfully in your app


1. In your application delegate's application:didFinishLaunchingWithOptions:
method, add the following code:

DBSession* dbSession = [[[DBSession alloc] initWithConsumerKey:@"<YOUR CONSUMER KEY>" consumerSecret:@"<YOUR CONSUMER SECRET>"] autorelease];
[DBSession setSharedSession:dbSession];

Note: you will need to #import "DropboxSDK.h" at the top of this file

2. Somewhere in your app, add an event to launch the login controller, which
should look something like this:

- (void)didPressLink {
DBLoginController* controller = [[DBLoginController new] autorelease];
[controller presentFromController:self];
}

Note: you will need to #import "DropboxSDK.h" at the top of this file


C. Creating folder in your dropbox using your App


1. In your .m file add the below code,

@interface DropBoxViewController () < DBLoginControllerDelegate, DBRestClientDelegate>

@property (nonatomic, readonly) DBRestClient* restClient;
@end
#pragma mark -
#pragma mark DBLoginControllerDelegate methods
- (void)loginControllerDidLogin:(DBLoginController*)controller
{
restClient = [self restClient];
[restClient setDelegate:self];
[def setBool:YES forKey:@"userLoggedToDropboxAccnt"];
[NSUserDefaults resetStandardUserDefaults];
[restClient loadMetadata:@"" withHash:photosHash];
}
- (void)loginControllerDidCancel:(DBLoginController*)controller {
}
- (DBRestClient*)restClient {
if (restClient == nil) {
restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
restClient.delegate = self;
}
return restClient;
}
#pragma mark -
#pragma mark DBRestClientDelegate methods
- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata {
[photosHash release];
photosHash = [metadata.hash retain];
NSMutableArray* newPhotoPaths = [NSMutableArray new];
for (DBMetadata* child in metadata.contents) {
[newPhotoPaths addObject:child.path];
}
[photoPaths release];
photoPaths = newPhotoPaths;
self.contentArray = photoPaths;
if([photoPaths containsObject:folderNmTxtField.text]){
}
else{
[restClient createFolder:folderNmTxtField.text];
}
}

photosHash is of type NSString defined in .h file
photoPaths is an NSArray defined in .h file

D.Uploading file in yur dropbox using your app


if restClient not initialized earlier, add the below code

restClient=[self restClient];
[restClient setDelegate:self];
[restClient loadMetadata:@"" withHash:photosHash];

for uploading,

[restClient uploadFile: filename toPath: (folder in which file is to be uploaded) fromPath: (path of the file to be uploaded);