当我按下一个按钮,然后按下另一个按钮时,声音会重叠。我该如何解决这个问题,以便在按下另一个声音时第一个声音停止?
- (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];
}
还请务必阅读苹果文档 http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)