Chudziutki
Chudziutki

Reputation: 41

iPhone AVAudioPlayer release EXC_BAD_ACCESS

I play sound making this:

NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];

In this buffer i have sound with aac format. Everything is ok, until I want to release it, and sometimes not always i get EXC_BAD_ACCESS

I release it in this way:

[player release];
free (buffer);

I think that player stil wants to do something with this data, but this data not longer exist after I make free (buffer);

But I don't know when make this free (buffer). If i remove this line everything is ok. But when i remove this free (buffer) i will have memory leaks:(

Best regards Chudziutki

Upvotes: 0

Views: 810

Answers (2)

vijay adhikari
vijay adhikari

Reputation: 2455

you can use below line of code,

NSData *dataToEncode = [NSData dataWithBytesNoCopy:base64buffer length:sizeof(base64buffer) freeWhenDone:YES];

Upvotes: 0

bbum
bbum

Reputation: 162722

(When putting code in a question, put 4 spaces in front of the line of code to format it as code. Inline code needs to be surrounding by little quote marks like this.)

If you have a crash, there will be a backtrace.

From the symptoms, you are apparently freeing the buffer before the AVAudioPlayer is done with it. You need to make sure that the audio player is entirely done with the buffer before you free the memory.

Likely, the most effective solution is something like:

buffer = malloc(...);
.... fill buffer ....
NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:YES];     
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
... let player play ...

Then, when you want the buffer to be deallocated, you stop and release the player:

[player stop];
[player release];
player = nil; // not necessary, but prevents a dangling pointer if player is an ivar and this isn't -dealloc

That is, let the audio player take ownership of the memory and the responsibility for free()ing it when done.

Upvotes: 1

Related Questions