最近要做一個項目,需要持續響鈴並振動,知道有私有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
