gpt4 book ai didi

ios - 内存管理 - 加载音效 - Cocoa Xcode

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

因此,我注意到我应该优化在我为 iOS 开发的小游戏中加载和使用声音的方式。

每次点击屏幕时,我都会加载“boing”声音并播放它,使 Sprite 跳跃(如马里奥)。
我希望每次都能播放声音,即使声音已经从上一次跳跃开始播放......

以下是我目前使用的两种方式:

第一次实现:

   //load the music from file
-(void)LoadMusic{
jumpSound = [[NSBundle mainBundle] pathForResource:@"boing" ofType:@"mp3"];
}

//call in viewDidLoad
- (void)viewDidLoad{
[self LoadMusic];
...
[super viewDidLoad];
}

//play sound when called
-(void)playSound{
jumpAffect = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];
[jumpAffect play];
}

//tap/touch to jump (& play sound)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event{
[self playSound];
jumpUp = 16;
}

第二次实现: ,这是相似的,除了我加载相同的文件 5 次,并循环到下一个(因此即使它已经在上一个 session 中也可以调用相同的声音效果)。
   int soundStage = 1;

//load the music from file
-(void)LoadMusic{
jumpSound = [[NSBundle mainBundle] pathForResource:@"Boing" ofType:@"mp3"];

jumpAffect = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];
jumpAffect.delegate = self;

jumpAffect2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];
jumpAffect2.delegate = self;

jumpAffect3 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];
jumpAffect3.delegate = self;

jumpAffect4 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];
jumpAffect4.delegate = self;

jumpAffect5 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];
jumpAffect5.delegate = self;
}

//call in viewDidLoad
- (void)viewDidLoad{
[self LoadMusic];
...
[super viewDidLoad];
}

//tap/touch to jump (& play sound)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event{

jumpUp = 16;

if(soundStage == 1){
[jumpAffect play];
soundStage = 2;
}
else if(soundStage == 2){
[jumpAffect2 play];
soundStage = 3;
}
else if(soundStage == 3){
[jumpAffect3 play];
soundStage = 4;
}
else if(soundStage == 4){
[jumpAffect4 play];
soundStage = 5;
}
else if(soundStage == 5){
[jumpAffect5 play];
soundStage = 1;
}

我想知道为什么哪个更好?我希望避免内存泄漏,并通过在点击屏幕时能够连续播放相同的声音来优化它。谢谢。

最佳答案

AVAudioPlayer 同时播放多个声音,每个音频播放器一个声音。所以更好的是在 touchesBegan 方法中加载/播放你的快速声音而不保留引用:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
NSString *jumpSound = [[NSBundle mainBundle] pathForResource:@"boing" ofType:@"mp3"];
AVAudioPlayer *jumpAffect = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];
[jumpAffect prepareToPlay];
[jumpAffect play];
jumpUp = 16;
}

关于ios - 内存管理 - 加载音效 - Cocoa Xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26288840/

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