【发布时间】:2014-05-27 05:34:41
【问题描述】:
您好,我正在构建一个应用程序,当用户摇晃它时它会播放声音。这是我的代码:
#import "ViewController.h"
#define accelerationThreshold 0.5
@interface ViewController ()
@property (strong, nonatomic) CMMotionManager *motionManager;
@end
@implementation ViewController
AVAudioPlayer *myAudio;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"sound"
ofType:@"wav"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
////
_motionManager = [[CMMotionManager alloc] init];
_motionManager.deviceMotionUpdateInterval = 0.5;
[_motionManager startDeviceMotionUpdatesToQueue: [NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error)
{
[self motionMethod:motion];
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"sound"
ofType:@"wav"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
////
_motionManager = [[CMMotionManager alloc] init];
_motionManager.deviceMotionUpdateInterval = 0.5;
[_motionManager startDeviceMotionUpdatesToQueue: [NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error)
{
[self motionMethod:motion];
}];
}
- (IBAction)playAudio:(id)sender {
[_audioPlayer play];
}
-(void)motionMethod:(CMDeviceMotion *)deviceMotion
{
CMAcceleration userAcceleration = deviceMotion.userAcceleration;
if (fabs(userAcceleration.x) > accelerationThreshold
|| fabs(userAcceleration.y) > accelerationThreshold
|| fabs(userAcceleration.z) > accelerationThreshold)
{
//Motion detected, handle it with method calls or additional
//logic here.
[self playAudio:self];
}
}
但是,我希望每次用户摇动设备时声音都覆盖当前声音,我该怎么做?因为目前它在声音结束时播放怪异,我该如何解决?
【问题讨论】:
-
请帮忙解决这个问题!
-
这个问题似乎是题外话,因为它甚至不看文档。
标签: ios xcode audio motion-detection