创建 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];
如果您需要进一步的帮助,请告诉我。