I’m trying to play a sound on a button click i’m using:
-(IBAction)sound {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Beat" ofType:@"wav"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
And;
#import <AVFoundation/AVAudioPlayer.h>
.h file;
- (IBAction) sound;
Do i forgot something?
I’ve had this problem before, and it is surprisingly deceptive due to the new way ARC works.
You’ve created theAudio within the method “sound”. However, the lifespan of this object only lasts till the method exits. Therefore, ARC destroys theAudio, before it even has a chance to play the sound.
Funnily enough, if you were doing this in pre-ARC, you’ll find that your sound plays, but you have a memory leak because theAudio isn’t getting released. Or you could release it when the callback occurs, but that kind of violates some memory management principles so I won’t stand for it.
You’ll need to have some sort of a “Mixer” class that handles/persists groups of audio players.