第三方微博客戶端Weico上面的每個(gè)按鈕點(diǎn)擊都有音效,今天來(lái)實(shí)現(xiàn)這個(gè)功能。
一、首先從weico的ipa包中獲取到音效文件,copy到自己的工程中來(lái)

二、添加AVFoundation.framework

三、自定義Button繼承自UIButton
WYButton.h:

WYButton.m:
#import"WYButton.h"
#import
@interfaceWYButton()
{
SystemSoundIDsoundFileObject;
}
@end
@implementationWYButton
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
{
[selfplaySoundEffect:@"weico_click"type:@"wav"];
}
- (void)playSoundEffect:(NSString*)name type:(NSString*)type
{
//得到音效文件的地址
NSString*soundFilePath =[[NSBundlemainBundle]pathForResource:nameofType:type];
//將地址字符串轉(zhuǎn)換成url
NSURL*soundURL = [NSURLfileURLWithPath:soundFilePath];
//生成系統(tǒng)音效id
AudioServicesCreateSystemSoundID((__bridgeCFURLRef)soundURL, &soundFileObject);
//播放系統(tǒng)音效
AudioServicesPlaySystemSound(soundFileObject);
}
@end

四、新建這個(gè)自定義Button類的實(shí)例,點(diǎn)擊的時(shí)候就附帶聲音效果了
代碼不多,有興趣的朋友可以自己敲敲看下效果。
音效播放的代碼轉(zhuǎn)自:http://soohu.github.io/ios/2015/05/02/iOS%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E2%80%94%E2%80%94%E6%B7%BB%E5%8A%A0%E9%9F%B3%E6%95%88%E5%92%8C%E6%92%AD%E6%94%BE%E9%9F%B3%E4%B9%90/
更新:
上述自定義Button的- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event方法中,在播放音效的代碼后要加上如下代碼,否則實(shí)例button點(diǎn)擊后,你所寫(xiě)的點(diǎn)擊效果將失效
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
{
[selfplaySound:@"weico_click"type:@"wav"];
[supertouchesBegan:toucheswithEvent:event];
}