gpt4 book ai didi

iphone - 多次按下时声音重叠

转载 作者:行者123 更新时间:2023-12-03 02:23:48 28 4
gpt4 key购买 nike

当我按下一个按钮,然后再按下另一个按钮时,声音会重叠。如何解决该问题,以便在按下另一个声音时停止播放第一个声音?

 - (void)playOnce:(NSString *)aSound {

NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
[theAudio setNumberOfLoops:0];
[theAudio setVolume:1.0];
[theAudio play];
}

- (void)playLooped:(NSString *)aSound {

NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
// loop indefinitely
[theAudio setNumberOfLoops:-1];
[theAudio setVolume:1.0];
[theAudio play];
[theAudio release];


}

最佳答案

在viewController的标题中声明您的AVAudioPlayer(每次播放声音时不要分配一个新的)。这样,您将拥有可以在StopAudio方法中使用的指针。

@interface myViewController : UIViewController <AVAudioPlayerDelegate> { 
AVAudioPlayer *theAudio;
}
@property (nonatomic, retain) AVAudioPlayer *theAudio;
@end


@implementation myViewController
@synthesize theAudio;
- (void)dealloc {
[theAudio release];
}
@end



- (void)playOnce:(NSString *)aSound {
NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
if(!theAudio){
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL];
}
[theAudio setDelegate: self];
[theAudio setNumberOfLoops:0];
[theAudio setVolume:1.0];
[theAudio play];
}

- (void)playLooped:(NSString *)aSound {
NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
if(!theAudio){
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL];
}
[theAudio setDelegate: self];
// loop indefinitely
[theAudio setNumberOfLoops:-1];
[theAudio setVolume:1.0];
[theAudio play];
}

- (void)stopAudio {
[theAudio stop];
[theAudio setCurrentTime:0];
}

还请务必阅读 Apple Docs

关于iphone - 多次按下时声音重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100531/

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