iOS自定义Button点击附带音效

第三方微博客户端Weico上面的每个按钮点击都有音效,今天来实现这个功能。

一、首先从weico的ipa包中获取到音效文件,copy到自己的工程中来

iOS自定义Button点击附带音效_第1张图片

二、添加AVFoundation.framework


iOS自定义Button点击附带音效_第2张图片

三、自定义Button继承自UIButton

WYButton.h:

iOS自定义Button点击附带音效_第3张图片

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];

//将地址字符串转换成url

NSURL*soundURL = [NSURLfileURLWithPath:soundFilePath];

//生成系统音效id

AudioServicesCreateSystemSoundID((__bridgeCFURLRef)soundURL, &soundFileObject);

//播放系统音效

AudioServicesPlaySystemSound(soundFileObject);

}

@end

iOS自定义Button点击附带音效_第4张图片


四、新建这个自定义Button类的实例,点击的时候就附带声音效果了


代码不多,有兴趣的朋友可以自己敲敲看下效果。


音效播放的代码转自: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方法中,在播放音效的代码后要加上如下代码,否则实例button点击后,你所写的点击效果将失效

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event

{

[selfplaySound:@"weico_click"type:@"wav"];

[supertouchesBegan:toucheswithEvent:event];

}

你可能感兴趣的:(iOS自定义Button点击附带音效)