Reputation: 14277
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?
Upvotes: 1
Views: 670
Reputation: 316
Try this and make sure to import Audio toolbox in your .h file
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"H1", CFSTR("WAV"), NULL);
if (soundFileURLRef){
CFStringRef url = CFURLGetString(soundFileURLRef);
}
UInt32 soundID;
AudioServicesCreateSystemSoundID)soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundIB);
Upvotes: 1
Reputation: 5495
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.
Upvotes: 2