gpt4 book ai didi

ios - 如何将音频彼此叠加?

转载 作者:行者123 更新时间:2023-12-03 02:34:08 26 4
gpt4 key购买 nike

您好,我正在构建一个可在用户摇动时播放声音的应用程序。这是我的代码:

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

但是,我希望每次用户摇动设备时声音都覆盖当前声音,我该怎么做?由于当前播放声音的时间很短,我该如何解决?

最佳答案

要使用AVAudioPlayer同时播放多个声音,您需要多个AVAudioPlayer。您只有一个,因此每次将其发送给play时,它仍然是唯一的播放器。

关于ios - 如何将音频彼此叠加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23881699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com