Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer gives no sound output

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.

like image 750
Josh Kahane Avatar asked Jun 01 '12 19:06

Josh Kahane


4 Answers

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;
like image 64
achi Avatar answered Oct 20 '22 23:10

achi


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];
}
like image 24
h3r3b Avatar answered Oct 20 '22 23:10

h3r3b


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.

like image 27
SmallChess Avatar answered Oct 20 '22 23:10

SmallChess


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.

like image 22
Pride Chung Avatar answered Oct 21 '22 01:10

Pride Chung