Josh Kahane
Josh Kahane

Reputation: 17169

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.

Upvotes: 12

Views: 8952

Answers (4)

esreli
esreli

Reputation: 5071

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;

Upvotes: 27

Pride Chung
Pride Chung

Reputation: 573

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.

Upvotes: 1

h3r3b
h3r3b

Reputation: 191

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];
}

Upvotes: 18

SmallChess
SmallChess

Reputation: 8146

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.

Upvotes: 9

Related Questions