I'm trying to use an AVPlayer in objective C in a SpriteKit app, but for some reason despite the URL being defined correctly, I can hear no music.
(This is being run from the gameviewcontroller)
-(void)viewDidLoad{
[super viewDidLoad];
[self prefersStatusBarHidden]; //hopefully stop an annoying bug.
NSLog(@"Is it on? %d", _playingMusic);
if(_playingMusic == 1){ //set audio to play if requested
NSString *soundPath1 = [[NSBundle mainBundle] pathForResource:@"new_twig_BK2_rehash" ofType:@"mp3"];
NSURL *soundURL1 = [NSURL fileURLWithPath: soundPath1];
AVAudioPlayer *BKMPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL1 error:nil];
BKMPlayer1.numberOfLoops = -1; //infinite loops
[BKMPlayer1 setVolume: 1.0];
[BKMPlayer1 stop];
[BKMPlayer1 setCurrentTime:0];
[BKMPlayer1 play];
}
}
Instead of creating the audio player in viewDidLoad
method, you should create a strong
property of audioPlayer
@property (nonatomic, strong) AVAudioPlayer *BKMPlayer1;
This is because, once the control goes out of the function, the audioPlayer is deallocated by the ARC.