I\'ve been pulling out my hair past three days to fix this problem. I\'ve checked lots of sample codes, read lots of tutorials, and googled and checked lots and lots of ques
So... I could finally fix this problem by creating a singleton
of the audioplayer
. This is how:
audioPlayer
from my NIKMasterViewController
class, that includes the audioPlayer
declaration and setting it in prepareForSegue
. NIKAudioPlayer
.In NIKAudioPlayer.h
:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface NIKAudioPlayer : NSObject <AVAudioPlayerDelegate>
{
AVAudioPlayer *currentPlayer;
}
@property (nonatomic, strong) AVAudioPlayer *currentPlayer;
+(NIKAudioPlayer *) sharedPlayer;
-(void)playURL:(NSURL*)url;
@end
In NIKAudioPlayer.m
:
#import "NIKAudioPlayer.h"
@implementation NIKAudioPlayer
@synthesize currentPlayer;
+(NIKAudioPlayer *) sharedPlayer
{
static NIKAudioPlayer* sharedPlayer;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedPlayer = [[NIKAudioPlayer alloc] init];
});
return sharedPlayer;
}
-(void)playURL:(NSURL*)url
{
[currentPlayer stop];
currentPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[currentPlayer prepareToPlay];
}
@end
Now in everywhere else in the code (in my case in NIKDetailViewController
) whenever I need to play an audio file, I call the sharedPlayer
from NIKAudioPlayer
:
[[NIKPlayer sharedPlayer] playURL:audioURL];
[[NIKPlayer sharedPlayer].currentPlayer prepareToPlay];
To put in a nutshell, replace all audioPlayer
s in NIKDetailViewController
with [NIKPlayer sharedPlayer].currentPlayer
, or even cast it and use it everywhere:
audioPlayer = [NIKPlayer sharedPlayer].currentPlayer