1.自定义一个UIButton类别命名为sound
2.导入AudioToolbox.framework静态库
运用知识点1.SystemSoundService
2.runtime 关联对象想了解的可以访问此网址 //www.greatytc.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
点击按钮触发音频并震动
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 原文链接http://www.cnblogs.com/kenshincui/p/4186022.html 音频在i...
- iOS开发中,页面传值是很常见的,但是页面传值你究竟知道多少呢?笔者这篇文章就是给大家介绍一下页面传值的具体方式,...
- SystemSoundID:SystemSoundID简介 AudioToolbox.framewor...