欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS持续振动 想停就停

程序员文章站 2022-07-15 16:41:35
...

最近要做一个项目,需要持续响铃并振动,知道有私有api可以使用,但无奈要上线,为了保险起见,果断放弃,在网上找了一个方法可以实现如下:

需要导入头文件:

#import <AudioToolbox/AudioToolbox.h>  

在播放振动的代码前面注册写下面一句代码:

 1 AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, soundCompleteCallback, NULL);  

其中soundCompleteCallback为播放系统振动或者声音后的回调,可以在里面继续播放振动实现持续振动的功能如下:

1
2
3
4
void soundCompleteCallback(SystemSoundID sound,voidvoid * clientData) { 
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  //震动 
    AudioServicesPlaySystemSound(sound); 

 但是问题来了,如何停止,其实之前我参考了别人做的,是直接调用如下代码停止:

1
2
3
AudioServicesRemoveSystemSoundCompletion(sound);
AudioServicesDisposeSystemSoundID(sound); AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);

 直接拷贝工程可用:

iOS持续振动 想停就停
            
    
    博客分类: ios  
 1 @interface ViewController ()
 2 {
 3     SystemSoundID sound;
 4 }
 5 //振动计时器
 6 @property (nonatomic,strong)NSTimer *_vibrationTimer;
 7 @end
 8 
 9 @implementation ViewController
10 @synthesize _vibrationTimer;
11 
12 - (void)viewDidLoad {
13     [super viewDidLoad];
14     // Do any additional setup after loading the view, typically from a nib.
15 
16 }
17 //开始响铃及振动
18 -(IBAction)startShakeSound:(id)sender{
19     
20     NSString *path = [[NSBundle mainBundle] pathForResource:@"2125" ofType:@"wav"];
21     AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &sound);
22     AudioServicesAddSystemSoundCompletion(sound, NULL, NULL, soundCompleteCallback, NULL);
23     AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
24     AudioServicesPlaySystemSound(sound);
25     
26     
27     /**
28      初始化计时器  每一秒振动一次
29 
30      @param playkSystemSound 振动方法
31      @return
32      */
33     _vibrationTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playkSystemSound) userInfo:nil repeats:YES];
34 }
35 //振动
36 - (void)playkSystemSound{
37     AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
38 }
39 //停止响铃及振动
40 -(IBAction)stopShakeSound:(id)sender{
41     
42     [_vibrationTimer invalidate];
43     AudioServicesRemoveSystemSoundCompletion(sound);
44     AudioServicesDisposeSystemSoundID(sound);
45     
46 }
47 //响铃回调方法
48 void soundCompleteCallback(SystemSoundID sound,void * clientData) {
49     AudioServicesPlaySystemSound(sound);
50 }