当我按下一个按钮,然后再按下另一个按钮时,声音会重叠。如何解决该问题,以便在按下另一个声音时停止播放第一个声音?
- (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/8101718/