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
网友评论