首页 > 代码库 > iOS持续振动 想停就停

iOS持续振动 想停就停

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

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

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

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

void soundCompleteCallback(SystemSoundID sound,voidvoid * clientData) {  
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  //震动  
    AudioServicesPlaySystemSound(sound);  
}  

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

 AudioServicesRemoveSystemSoundCompletion(sound);
 AudioServicesDisposeSystemSoundID(sound); AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
 AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);

 但我遇到了个奇葩的问题,是在ios10上测试,其它版本我没有手机没有进行测试,问题是我发现调用停止方法后,并没有立即停止,停止的时间和你播放振动的时间成正比,振动时间越长,调用停止后,还要继续振动一段时间才停止,让人很头疼所以我进行了一下改造后,实现了需要的功能,用计时器实现,仅供初学者参考,大神勿喷,直接拷贝工程可用:

 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 }

其中铃声需要替换掉,或者去掉响铃 Demo:https://github.com/wtfubj/ContinuousVibrationDemo.git

 

iOS持续振动 想停就停