工具类的封装方法1

 

 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

 

转载于:https://www.cnblogs.com/yangshun-work/p/5058442.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值