首页 > 代码库 > 音频类 单例
音频类 单例
.h文件
#import <Foundation/Foundation.h>
@interface PLMsoundTool : NSObject<NSCopying>
- (void)playSongWithName:(NSString *)name;
+ (instancetype)shareSoundTool;
@end
.m文件
#import "PLMsoundTool.h"
#import <AudioToolbox/AudioToolbox.h>
@interface PLMsoundTool()
@property (nonatomic, strong) NSMutableDictionary *soundList;
@end
@implementation PLMsoundTool
static PLMsoundTool *_instance;
- (NSMutableDictionary *)soundList
{
if (_soundList == nil) {
_soundList = [NSMutableDictionary dictionary];
}
return _soundList;
}
- (void)playSongWithName:(NSString *)name
{
SystemSoundID soundId = [self.soundList[name] unsignedIntValue];
AudioServicesPlaySystemSound(soundId);
}
+ (instancetype)shareSoundTool
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[PLMsoundTool alloc]init];
});
return _instance;
}
+ (id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
- (id)init
{
if (self = [super init]) {
[self loadAllSounds];
}
return self;
}
- (void)loadAllSounds
{
NSString *path = [[NSBundle mainBundle].bundlePath stringByAppendingPathComponent:@"Sounds.bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
[files enumerateObjectsUsingBlock:^(NSString *fileName, NSUInteger idx, BOOL *stop) {
SystemSoundID soundId = [self creatSoundIdWithFileName:fileName];
[self.soundList setObject:@(soundId) forKey:fileName];
}];
}
- (SystemSoundID)creatSoundIdWithFileName:(NSString *)fileName
{
SystemSoundID soundId = 0;
NSURL *url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil subdirectory:@"Sounds.bundle"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundId);
return soundId;
}
- (id)copyWithZone:(struct _NSZone *)zone
{
return _instance;
}
#pragma mark - MRC需要重写的方法,目的就是覆盖系统默认的内存管理方法
// 让MRC的程序代码和ARC的共存!
#if !__has_feature(objc_arc)
- (id)retain { return self; }
- (id)autorelease { return self; }
- (NSUInteger)retainCount { return UINT_MAX; }
- (oneway void)release{}
#endif
@end