1.自定义一个UIButton类别命名为sound
2.导入AudioToolbox.framework静态库
运用知识点1.SystemSoundService
2.runtime 关联对象想了解的可以访问此网址 http://www.jianshu.com/p/c68cc81ef763
例子:在.h文件中
#importtypedef void(^UIButtonTounchWithCalBlock)(NSInteger index);
@interface UIButton (Sound)
-(void)buttonWithPath:(NSString *)path;
@end
在.m文件中#import "UIButton+Sound.h"#import#importstatic const void *UIButtonSoundIDkey=&UIButtonSoundIDkey;
@implementation UIButton (Sound)
-(void)buttonWithPath:(NSString *)path{
objc_setAssociatedObject(self, UIButtonSoundIDkey, path, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(actionTouch:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)actionTouch:(UIButton *)sender{
NSString * path =objc_getAssociatedObject(self, UIButtonSoundIDkey);
SystemSoundID soundID;
NSURL * url =[NSURL URLWithString:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
AudioServicesPlayAlertSound(soundID);
}
ControllerView.m文件中
#define UIScreenHeight [UIScreen mainScreen].bounds.size.height
#define UIScreenWidth [UIScreen mainScreen].bounds.size.width
#import "ViewController.h"
#import "UIButton+Sound.h"
@interface ViewController ()
@property(strong,nonatomic)UIButton * soundButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.soundButton];
}
-(UIButton *)soundButton{
if (!_soundButton) {
_soundButton =[UIButton buttonWithType:UIButtonTypeCustom];
_soundButton.frame =CGRectMake((UIScreenWidth-100)/2, 100, 100, 45);
[_soundButton setBackgroundColor:[UIColor redColor]];
[_soundButton setTitle:@"声音" forState:UIControlStateNormal];
NSString * path =[[NSBundle mainBundle]pathForResource:@"4157" ofType:@"mp3"];
[_soundButton buttonWithPath:path];
}
return _soundButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
点击按钮触发音频并震动
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 原文链接http://www.cnblogs.com/kenshincui/p/4186022.html 音频在i...
- iOS开发中,页面传值是很常见的,但是页面传值你究竟知道多少呢?笔者这篇文章就是给大家介绍一下页面传值的具体方式,...
- SystemSoundID:SystemSoundID简介 AudioToolbox.framewor...