您的位置:首页 > 移动开发 > IOS开发

iOS开发 - 播放系统音效、自定义音效

2012-08-27 17:01 561 查看
播放系统音效、自定义音效工具类

需求大致分为三种:

1.震动

2.系统音效(无需提供音频文件)

3.自定义音效(需提供音频文件)

我的工具类的封装:

01
//
02
//
WQPlaySound.h
03
//
WQSound
04
//
05
//
Createdby念茜on12-7-20.
06
//
Copyright(c)2012年__MyCompanyName__.Allrightsreserved.
07
//
08
09
#import
<UIKit/UIKit.h>
10
#import
<AudioToolbox/AudioToolbox.h>
11
12
@interface
WQPlaySound:NSObject
13
{
14
SystemSoundID
soundID;
15
}
16
17
/**
18
*
@brief为播放震动效果初始化
19
*
20
*
@returnself
21
*/
22
-(id)initForPlayingVibrate;
23
24
/**
25
*
@brief为播放系统音效初始化(无需提供音频文件)
26
*
27
*
@paramresourceName系统音效名称
28
*
@paramtype系统音效类型
29
*
30
*
@returnself
31
*/
32
-(id)initForPlayingSystemSoundEffectWith:(NSString
*)resourceNameofType:(NSString*)type;
33
34
/**
35
*
@brief为播放特定的音频文件初始化(需提供音频文件)
36
*
37
*
@paramfilename音频文件名(加在工程中)
38
*
39
*
@returnself
40
*/
41
-(id)initForPlayingSoundEffectWith:(NSString
*)filename;
42
43
/**
44
*
@brief播放音效
45
*/
46
-(
void
)play;
47
48
@end
01
//
02
//
WQPlaySound.m
03
//
WQSound
04
//
05
//
Createdby念茜on12-7-20.
06
//
Copyright(c)2012年__MyCompanyName__.Allrightsreserved.
07
//
08
09
#import
"WQPlaySound.h"
10
11
@implementation
WQPlaySound
12
13
-(id)initForPlayingVibrate
14
{
15
self
=[superinit];
16
if
(self)
{
17
soundID
=kSystemSoundID_Vibrate;
18
}
19
return
self;
20
}
21
22
-(id)initForPlayingSystemSoundEffectWith:(NSString
*)resourceNameofType:(NSString*)type
23
{
24
self
=[superinit];
25
if
(self)
{
26
NSString
*path=[[NSBundlebundleWithIdentifier:@
"com.apple.UIKit"
]
pathForResource:resourceNameofType:type];
27
if
(path)
{
28
SystemSoundID
theSoundID;
29
OSStatus
error=AudioServicesCreateSystemSoundID((__bridgeCFURLRef)[NSURLfileURLWithPath:path],&theSoundID);
30
if
(error
==kAudioServicesNoError){
31
soundID
=theSoundID;
32
}
else
{
33
NSLog(@
"Failed
tocreatesound"
);
34
}
35
}
36
37
}
38
return
self;
39
}
40
41
-(id)initForPlayingSoundEffectWith:(NSString
*)filename
42
{
43
self
=[superinit];
44
if
(self)
{
45
NSURL
*fileURL=[[NSBundlemainBundle]URLForResource:filenamewithExtension:nil];
46
if
(fileURL
!=nil)
47
{
48
SystemSoundID
theSoundID;
49
OSStatus
error=AudioServicesCreateSystemSoundID((__bridgeCFURLRef)fileURL,&theSoundID);
50
if
(error
==kAudioServicesNoError){
51
soundID
=theSoundID;
52
}
else
{
53
NSLog(@
"Failed
tocreatesound"
);
54
}
55
}
56
}
57
return
self;
58
}
59
60
-(
void
)play
61
{
62
AudioServicesPlaySystemSound(soundID);
63
}
64
65
-(
void
)dealloc
66
{
67
AudioServicesDisposeSystemSoundID(soundID);
68
}
69
@end
调用方法步骤:

1.加入AudioToolbox.framework到工程中

2.调用WQPlaySound工具类

2.1震动

1
WQPlaySound
*sound=[[WQPlaySoundalloc]initForPlayingVibrate];
2
[sound
play];

2.2系统音效,以Tock为例

1
WQPlaySound
*sound=[[WQPlaySoundalloc]initForPlayingSystemSoundEffectWith:@
"Tock"
ofType:@
"aiff"
];
2
[sound
play];

2.3自定义音效,将tap.aif音频文件加入到工程

1
WQPlaySound
*sound=[[WQPlaySoundalloc]initForPlayingSoundEffectWith:@
"tap.aif"
];
2
[sound
play];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: