搖一搖是個很討喜的互動方式。之前在網頁端做過用 JavaScript 判斷的版本,但到了 iOS 原生開發,做法完全不同——系統已經內建了搖動偵測,只要覆寫一個方法就能取得事件。本文示範如何偵測搖動並播放音效與震動回饋。
iOS 的 motion 事件會透過 motionBegan:withEvent: 傳遞給 first responder。當 motion 等於 UIEventSubtypeMotionShake 時,就代表使用者搖動了裝置。
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion == UIEventSubtypeMotionShake) {
NSLog(@"搖一搖,哈哈哈");
[self playSoundEffect:@"yaoyiyao"];
}
}
- (void)playSoundEffect:(NSString *)name {
// 1. 取得系統聲音 ID
SystemSoundID soundID;
/**
* inFileUrl : 音訊檔的 url
* outSystemSoundID : 聲音 id
* 此函式會把音效檔加入系統音訊服務,並回傳一個長整數 ID
*/
NSString *audioFile = [[NSBundle mainBundle] pathForResource:name ofType:@"m4r"];
NSURL *fileUrl = [NSURL fileURLWithPath:audioFile];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
// 2. 播放音訊
AudioServicesPlaySystemSound(soundID);
// 3. 播放震動
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
// 若想同時播放音效並震動,可改用:
// AudioServicesPlayAlertSound(soundID);
}
yaoyiyao 是檔名,副檔名為 .m4r。記得把檔案加入專案,並確認 Target Membership 已勾選,否則執行期會找不到檔案而導致 soundID 為 0。AudioServicesCreateSystemSoundID 建立後,若不再使用應呼叫 AudioServicesDisposeSystemSoundID 釋放,避免反覆搖動造成資源累積。canBecomeFirstResponder 回傳 YES 並在 viewDidAppear: 中呼叫 becomeFirstResponder。模擬器也支援搖動,操作方式:Hardware → Shake Gesture。這樣就能像真機一樣觸發搖一搖事件,不必每次都拿著實機甩。
微信的搖一搖音效檔網路上可以找到,放入專案後替換檔名即可。