如何将音频叠加在一起?

时间:2014-05-27 05:34:42

标签: ios xcode audio motion-detection

您好我正在构建一个应用程序,当用户摇动它时会发出声音。这是我的代码:

#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];
}
}

但是,每当用户摇动设备时,我希望声音覆盖当前声音,我该怎么做?因为目前声音播放的时间很长,我该如何解决?

1 个答案:

答案 0 :(得分:0)

要与AVAudioPlayer同时播放多个声音,您需要多个AVAudioPlayer。你只有一个,所以每次你发送它play它仍然是唯一一个播放。