gpt4 book ai didi

iphone - 如何使用一个 Action 循环播放多种声音?

转载 作者:行者123 更新时间:2023-11-29 04:43:11 26 4
gpt4 key购买 nike

现在,我通过一个 Action 、按下按钮、加速计等播放一种声音。

我想知道如何通过用户启动的单个操作循环播放多种声音(我的项目使用了 3 种声音)。

我目前正在使用下面所示的代码,它的目的是为每个用户操作播放一个声音。我以前没有在项目中使用过 NSArray,所以如果您使用它,请提供任何详细信息。

NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/Jet.wav", [[NSBundle mainBundle] resourcePath]]];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;

if (audioPlayer == nil)
NSLog(@"%@", [error description]);
else
[audioPlayer play];

最佳答案

如果您只使用 3 个声音,那么您可以只使用 NSString 的 C 数组,但如果您需要动态数量的声音,那么您应该改为使用 >NSArray

// .m
NSString *MySounds[3] = {
@"sound1.wav",
@"sound2.wav",
@"sound3.wav",
};

@implementation ...

然后在你的方法中你需要添加一些额外的逻辑

- (void)playSound;
{
NSString *path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], [self nextSoundName]];

NSURL *url = [NSURL fileURLWithPath:path];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;

if (audioPlayer == nil) {
NSLog(@"%@", [error description]);
} else {
[audioPlayer play];
}
}

- (NSString *)nextSoundName;
{
static NSInteger currentIndex = -1;

if (++currentIndex > 2) {
currentIndex = 0;
}

return MySounds[currentIndex];
}

关于iphone - 如何使用一个 Action 循环播放多种声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10051541/

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