Search code examples
objective-cxcodeaudioexc-bad-accesscore-audio

EXC_BAD_ACCESS on ExtAudioFileWriteAsync


I have added the following code at the end of the Mic / Line In Audio Rendering Callback.

But the app keeps crashing with EXC_BAD_ACCESS on :

err = ExtAudioFileWriteAsync(mOutputAudioFile, inNumberFrames, ioData);

The rest of the code is as follows :

ExtAudioFileRef mOutputAudioFile;
    AudioFileID mAfid;
    NSLog(@"Writing output to file ....");

    NSArray *dirPaths;
    NSString *docsDir;
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    NSLog(@"docDir = %@", docsDir);
    NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound.caf"];
    NSURL *inPath = [NSURL fileURLWithPath:soundFilePath];
    NSLog(@"Output file path is : %@", inPath);

    AudioStreamBasicDescription mStreamFormat;

    mStreamFormat.mChannelsPerFrame     = 1;
    mStreamFormat.mSampleRate           = 44100.00;
    mStreamFormat.mFormatID             = kAudioFormatLinearPCM;
    mStreamFormat.mFormatFlags          = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
    mStreamFormat.mBitsPerChannel       = 16;
    mStreamFormat.mBytesPerFrame        = 2;
    mStreamFormat.mFramesPerPacket      = 1;
    mStreamFormat.mBytesPerPacket       = 2;
    mStreamFormat.mReserved             = 0;


    err = AudioFileCreateWithURL((CFURLRef)inPath, kAudioFileCAFType, &mStreamFormat, kAudioFileFlags_EraseFile, &mAfid);
    if (err != noErr) {
        NSLog(@"ERROR : Audio file could not be created !! %d", (int)err);

    }
    err = ExtAudioFileWrapAudioFileID(mAfid, true, &mOutputAudioFile);
    err = ExtAudioFileSetProperty(mOutputAudioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(AudioStreamBasicDescription), &mStreamFormat);
    if (ioData) {
        err = ExtAudioFileWriteAsync(mOutputAudioFile, inNumberFrames, ioData);
        if (err != noErr) {
            NSLog(@"ERROR : Audio file could not be written !! %d", (int)err);
        }
    }
    else {

        NSLog(@"No ioData found");
    }
    NSLog(@"Done writing output to file ....");

I have tried almost everything with this. I would be extremely thankful if somebody could help me resolve it. Thanks !

UPDATE 1:

If I use ExtAudioFileWrite instead of ExtAudioFileWriteAsync, the app doesn't crash, but returns error -50 for ExtAudioFileWrite.

I still have no idea what's happening with it. Any help in this regard is much appreciated.

Thanks.


Solution

  • The sample code posted in the answer here answered all my questions :

    Can anybody help me in recording iPhone output sound through Audio Unit

    Thanks so much everyone for your help.