Search code examples
objective-cavfoundationavaudioplayerbackground-music

How to deal with AVAudioPlayer correctly in objective-c


i'm working on little game, and i've got problem with background music. I use AVAudioPlayer to play loop music. It's look like below:

NSString *path = [[NSBundle mainBundle] pathForResource:@"background" ofType:@"ogg"];
NSError *error;

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:&error];

NSLog(@"%@", [error description]);

[player setNumberOfLoops:-1];
player.delegate = self;
[player play];

I've got in Supproting Files file background.ogg, background.mp3, background.wav and no one plays. What is wrong with it?

And when i use NSLog to print description error i've got:

Error Domain=NSOSStatusErrorDomain Code=1954115647 "The operation couldn’t be completed. (OSStatus error 1954115647.)"

Please help.


Solution

  • That was so easy. There is one more thing. When you use e.g NSTimer you must ivalidate it in some place. When you use AVAudioPlayer you have to stop it in some place.

    [player stop];