I have imported audio toolbox and avfoundation to my class and added the frameworks to my project and am using this code to play a sound:
- (void)playSound:(NSString *)name withExtension:(NSString *)extension
{
NSURL* soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:name ofType:extension]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
audioPlayer.delegate = self;
audioPlayer.volume = 1.0;
[audioPlayer play];
}
I call it like this:
[self playSound:@"wrong" withExtension:@"wav"];
However I get zero sound.
Updated answer:
I've got the issue. It's with ARC and has nothing to do with prepareForPlay. Simply make a strong reference to it and it will work.
as stated below by user: Kinderchocolate
:)
In code:
.h
~
@property (nonatomic, strong) AVAudioPlayer *player;
.m
~
@implementation
@synthesize _player = player;
Yes, ARC was the problem for me too. I solved just adding:
In .h
@property (strong, nonatomic) AVAudioPlayer *player;
In .m
@synthesize player;
-(void)startMusic{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Riddls" ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //infinite
[player play];
}
I've got the issue. It's with ARC and has nothing to do with prepareForPlay. Simply make a strong reference to it and it will work.
If you declare your AVAudioPlayer in a class method like -viewDidLoad, and ARC is on, the player will be released right after -viewDidLoad and become nil, (-(BOOL)play
method won't block a thread) this will happend in milliseconds, obvious "nil" can't play anything, so you won't even hear a sound.
Better declare the player as ViewController's @property
or make it as a global singleton, anything can last longer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With