#import "PlayAudioTool.h"
#import <AVFoundation/AVFoundation.h>
//定义一个全局的缓存池变量, 因为音效它会一直添加到内存中,当继续添加音效时, 内存储存不了,此时就会将内存底部的一个音效移除, 然后添加新的, 虽然这个能够存储音效, 但是对与内存而言,任然是饱满, 所以我们这个就定义一个缓存池, 第一是不让相同的音效重复加载到内存中区,第二是当内存发出内存警告时, 我们可以在applicationDidReceiveMemoryWarning:(UIApplication *)application这个方法中将缓存池中的音频对象移除,从而达到内存优化的目的
static NSMutableDictionary * dict ;
@implementation PlayAudioTool
//当类被加载, 也就是被编译是就会调用这个方法, 给缓存池字典初始化
+(void)load{
dict = [NSMutableDictionary dictionary];
}
+(void)playAudioWithFileName:(NSString *)fileName isAlert:(BOOL)alert{
//获取音效资源
NSString * path = [[NSBundle mainBundle]pathForResource:fileName ofType:nil];
NSURL * url = [NSURL fileURLWithPath:path];
//创建一个soundID
SystemSoundID sound ;
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &sound);
if (alert) {
//播放时带振动
AudioServicesPlayAlertSound(sound);
}else{
//播放
//播放是音效, 不震动
AudioServicesPlaySystemSound(sound);
}
}
+(void)clearMeary {
for (NSString * key in dict) {
SystemSoundID sound = [dict[key]unsignedIntValue];
AudioServicesDisposeSystemSoundID(sound);
}
//将缓存池中的所有对象移除
[dict removeAllObjects];
}
原文:http://www.cnblogs.com/yuwei0911/p/5449270.html