views:

148

answers:

3

I've read a number of posts regarding how to 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

+2  A: 

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.

Frank Shearar
A: 

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.

Felixyz
+1  A: 

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];
        }
    }
}
Zoran Simic
Thanks for this answer. This is another acceptable solution (wish I could mark both right)
wgpubs