1 // 2 // YSvoiceTool.h 3 // audio 4 // 5 // Created by ys on 15/12/18. 6 // Copyright (c) 2015年 ys. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 @interface YSvoiceTool : NSObject 12 13 /** 14 * 播放音效 15 * 16 * @param fileName 音效文件名 17 */ 18 +(void)playSoundWithName:(NSString *)fileName; 19 20 21 /** 22 * 销毁音效 23 * 24 * @param fileName 音效文件名 25 */ 26 +(void)disposeSoundWithName:(NSString *)fileName; 27 28 @end
1 // 2 // YSvoiceTool.m 3 // audio 4 // 5 // Created by ys on 15/12/18. 6 // Copyright (c) 2015年 ys. All rights reserved. 7 // 8 9 #import "YSvoiceTool.h" 10 #import <AVFoundation/AVFoundation.h> 11 12 @implementation YSvoiceTool 13 14 // 字典: fileName作为key, soundID作为value 15 // 存放所有的音频ID 16 static NSMutableDictionary *_soundsDict; 17 18 +(void)initialize 19 { 20 _soundsDict = [NSMutableDictionary dictionary]; 21 } 22 23 +(void)playSoundWithName:(NSString *)fileName 24 { 25 if (!fileName) { 26 return; 27 } 28 // 1.从字典中取出soundID 29 SystemSoundID soundID = [_soundsDict[fileName] unsignedLongValue]; 30 if (!soundID) {// 创建 31 // 加载音效文件 32 NSURL *url = [NSURL URLWithString:[[NSBundle mainBundle]pathForResource:fileName ofType:nil]]; 33 if (!url) { 34 return; 35 } 36 // 创建音效ID 37 AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID); 38 // 放入字典 39 _soundsDict[fileName] = @(soundID); 40 } 41 // 2.播放 42 AudioServicesPlaySystemSound(soundID); 43 44 } 45 46 47 +(void)disposeSoundWithName:(NSString *)fileName 48 { 49 if (!fileName) { 50 return; 51 } 52 SystemSoundID soundID = [_soundsDict[fileName] unsignedLongValue]; 53 if (soundID) { 54 // 销毁音效ID 55 AudioServicesDisposeSystemSoundID(soundID); 56 // 从字典中移除 57 [_soundsDict removeObjectForKey:fileName]; 58 } 59 60 } 61 62 @end