你好
我希望在用户移动设备时改变灵敏度。目前它还不是很敏感,我相信它是默认的。我希望它更加灵敏,因此当用户稍微摇动手机时,声音就会播放。

这是代码

谢谢

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self becomeFirstResponder];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(motion == UIEventSubtypeMotionShake)
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"whip" ofType:@"wav"];
        if (theAudio) [theAudio release];
        NSError *error = nil;
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
        if (error)
            NSLog(@"%@",[error localizedDescription]);
        theAudio.delegate = self;
        [theAudio play];
    }
}

最佳答案

首先,请确保您的界面采用UIAccelerobeterDelegate协议。

@interface MainViewController : UIViewController <UIAccelerometerDelegate>


现在在您的实现中:

//get the accelerometer
self.accelerometer = [UIAccelerometer sharedAccelerometer];
self.accelerometer.updateInterval = .1;
self.accelerometer.delegate = self;


实现委托方法:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
  float x = acceleration.x;
  float y = acceleration.y;
  float b = acceleration.z;

  // here you can write simple change threshold logic
  // so you can call trigger your method if you detect the movement you're after
}


加速度计返回的x,y和z的值始终是-1.0到正1.0之间的浮点。您应该调用NSLog并将其x,y和z值输出到控制台,以便对它们的含义有所了解。然后,您可以开发一种简单的方法来检测运动。

关于iphone - iPhone加速度计更改灵敏度-Cocoa Touch,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5722157/

10-12 18:09