點擊按鈕觸發(fā)音頻并震動

1.自定義一個UIButton類別命名為sound

2.導(dǎo)入AudioToolbox.framework靜態(tài)庫


運用知識點

1.SystemSoundService

2.runtime 關(guān)聯(lián)對象想了解的可以訪問此網(wǎng)址 http://www.itdecent.cn/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

原碼下載網(wǎng)址:https://github.com/yishhong/soundVibrationDemo.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容