次のようにSingletonClass.hファイルを作成します
#import <Foundation/Foundation.h>
#import "AVFoundation/AVFoundation.h"
@interface SingletonClass : NSObject
{
BOOL is_sound_enable;
AVAudioPlayer *audioPlayer;
}
@property (nonatomic,assign) BOOL is_sound_enable;
@property (nonatomic,retain) AVAudioPlayer *audioPlayer;
+ (SingletonClass *)sharedInstance;
-(void)checkAndPlayMusic;
-(void)loadNewFile:(NSURL*)newFileURL;
@end
次のようにSingletonClass.mファイルを作成します
#import "SingletonClass.h"
@implementation SingletonClass
@synthesize is_sound_enable;
@synthesize audioPlayer;
#pragma mark -
#pragma mark Singleton Variables
static SingletonClass *singletonHelper = nil;
#pragma mark -
#pragma mark Singleton Methods
- (id)init {
if ((self = [super init])) {
is_sound_enable = YES;
NSString *strPath = @""; //<-- Assign path here
NSURL *url = [NSURL URLWithString:strPath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer prepareToPlay];
audioPlayer.numberOfLoops = -1; //<-- This will set it to infinite playing.
}
return self;
}
+ (SingletonClass *)sharedInstance {
@synchronized(self) {
if (singletonHelper == nil) {
[[self alloc] init]; // assignment not done here
}
}
return singletonHelper;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (singletonHelper == nil) {
singletonHelper = [super allocWithZone:zone];
// assignment and return on first allocation
return singletonHelper;
}
}
// on subsequent allocation attempts return nil
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
//- (void)release {
- (void)dealloc {
[audioPlayer release];
[super dealloc];
}
- (id)autorelease {
return self;
}
-(void)resumeBackgroundMusic
{
//Your code
NSLog(@"Playing music");
[self.audioPlayer play];
}
-(void)pauseBackgroundMusic
{
//Your code here
NSLog(@"Paused music");
[self.audioPlayer pause];
}
-(void)checkAndPlayMusic
{
if(self.is_sound_enable)
[self resumeBackgroundMusic];
else
[self pauseBackgroundMusic];
}
//Added this new method to load new music file.
-(void)loadNewFile:(NSURL*)newFileURL
{
if(self.audioPlayer)
[self.audioPlayer release];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:newFileURL error:nil];
[audioPlayer prepareToPlay];
audioPlayer.numberOfLoops = -1;
}
@end
今あなたがしなければならないことは
SingletonClass *sgHelper = [SingletonClass sharedInstance];
sgHelper.is_sound_enable = NO; //<--Set here NO or YES according to your requirement and music will be played accordingly.
[sgHelper checkAndPlayMusic];
さらにサポートが必要な場合はお知らせください。