开发者

How to play an audio file ONLY while user is shaking iPhone?

开发者 https://www.devze.com 2022-12-25 06:46 出处:网络
I\'ve read a number of posts regarding how to开发者_JAVA技巧 detect shakes but I\'m not sure: What is currently the best way to detect shakes?

I've read a number of posts regarding how to开发者_JAVA技巧 detect shakes but I'm not sure:

  1. What is currently the best way to detect shakes?

    • and -
  2. How to play an audio file ONLY while the user is shaking the iPhone?

Anyone have an advice, examples/tutorials or sample code?

Thanks


You can implement something like this below in a controller (or any UIResponder actually...). These are available in 3.0 and later. You don't have to go down to the level of the accelerometer if you don't want to do advanced stuff, depends on how much detail you want from the shaking.

- (void)viewDidAppear:(BOOL)animated {
    [self becomeFirstResponder];
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion==UIEventSubtypeMotionShake) {
        if ([self paused]) {
            [self play];
        }
    }
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion==UIEventSubtypeMotionShake) {
        if ([self playing]) {
            [self pause];
        }
    }
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion==UIEventSubtypeMotionShake) {
        if ([self playing]) {
            [self pause];
        }
    }
}


Use the UIAccelerometer and implement the UIAccelerometerDelegate protocol in your class. Perhaps you could do something like this:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acc {
  float twoGs = 2.0;
  if ((acc.x * acc.x) + (acc.y * acc.y) + (acc.z * acc.z) > twoGs * twoGs) {
    if ([self paused]) {
      [self play];
    }
  } else {
    if ([self playing]) {
      [self pause];
    }
  }
}

for suitable implementations of the pause, paused, play, playing selectors.


This has been answered before here. I'm using a modified version of the code proposed there, and it works great. Note that in upcoming versions of the OS, you will be able to detect shake gestures through the standard API.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号