美文网首页
点击按钮触发音频并震动

点击按钮触发音频并震动

作者: JamesYi | 来源:发表于2016-05-24 17:17 被阅读131次

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

原码下载网址:https://github.com/yishhong/soundVibrationDemo.git

相关文章

网友评论

      本文标题:点击按钮触发音频并震动

      本文链接:https://www.haomeiwen.com/subject/rjmzrttx.html